instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private List<OperationParameter> getOperationParameters(Parameter[] parameters, @Nullable String[] names) { List<OperationParameter> operationParameters = new ArrayList<>(parameters.length); for (int i = 0; i < names.length; i++) { String name = names[i]; Assert.state(name != null, "'name' must not be null"); operationParameters.add(new OperationMethodParameter(name, parameters[i])); } return Collections.unmodifiableList(operationParameters); } @Override public int getParameterCount() { return this.operationParameters.size(); } @Override
public OperationParameter get(int index) { return this.operationParameters.get(index); } @Override public Iterator<OperationParameter> iterator() { return this.operationParameters.iterator(); } @Override public Stream<OperationParameter> stream() { return this.operationParameters.stream(); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoke\reflect\OperationMethodParameters.java
1
请完成以下Java代码
protected void customizeHUEditorView(@NonNull final HUEditorViewBuilder huViewBuilder) { huViewBuilder .addAdditionalRelatedProcessDescriptor(createProcessDescriptor(de.metas.ui.web.picking.husToPick.process.WEBUI_Picking_HUEditor_PickHU.class)) .addAdditionalRelatedProcessDescriptor(createProcessDescriptor(de.metas.ui.web.picking.husToPick.process.WEBUI_HUsToPick_PickCU.class)) .addAdditionalRelatedProcessDescriptor(createProcessDescriptor(de.metas.ui.web.picking.husToPick.process.WEBUI_Picking_HUEditor_Create_M_Source_HUs.class)) .addAdditionalRelatedProcessDescriptor(createProcessDescriptor(de.metas.ui.web.picking.husToPick.process.WEBUI_HUsToPick_Weight.class)) // .clearOrderBys() .orderBy(DocumentQueryOrderBy.builder().fieldName(HUEditorRow.FIELDNAME_IsReserved).ascending(false).nullsLast(true).build()) .orderBy(createBestBeforeDateOrderBy(huViewBuilder.getParameter(HUsToPickViewFilters.PARAM_BestBeforePolicy))) .orderBy(DocumentQueryOrderBy.byFieldName(HUEditorRow.FIELDNAME_M_HU_ID)); } private static DocumentQueryOrderBy createBestBeforeDateOrderBy(@Nullable final ShipmentAllocationBestBeforePolicy bestBeforePolicy) { final ShipmentAllocationBestBeforePolicy bestBeforePolicyEffective = CoalesceUtil.coalesce(bestBeforePolicy, ShipmentAllocationBestBeforePolicy.Expiring_First); if (bestBeforePolicyEffective == ShipmentAllocationBestBeforePolicy.Expiring_First) { return DocumentQueryOrderBy.builder().fieldName(HUEditorRow.FIELDNAME_BestBeforeDate).ascending(true).nullsLast(true).build(); } else if (bestBeforePolicyEffective == ShipmentAllocationBestBeforePolicy.Newest_First) { return DocumentQueryOrderBy.builder().fieldName(HUEditorRow.FIELDNAME_BestBeforeDate).ascending(false).nullsLast(true).build(); } else { throw new AdempiereException("Unknown best before policy: " + bestBeforePolicyEffective); } } @Override public IView filterView(final @NonNull IView view, final @NonNull JSONFilterViewRequest filterViewRequest, final @NonNull Supplier<IViewsRepository> viewsRepo) {
final CreateViewRequest.Builder filterViewBuilder = CreateViewRequest.filterViewBuilder(view, filterViewRequest); if (view instanceof HUEditorView) { final HUEditorView huEditorView = HUEditorView.cast(view); filterViewBuilder.setParameters(huEditorView.getParameters()); final ViewId parentViewId = huEditorView.getParentViewId(); final IView parentView = viewsRepo.get().getView(parentViewId); if (parentView instanceof PickingSlotView) { final PickingSlotView pickingSlotView = PickingSlotView.cast(parentView); filterViewBuilder.setParameter(HUsToPickViewFilters.PARAM_CurrentShipmentScheduleId, pickingSlotView.getCurrentShipmentScheduleId()); } } final CreateViewRequest createViewRequest = filterViewBuilder.build(); return createView(createViewRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\HUsToPickViewFactory.java
1
请完成以下Java代码
public String getUPC () { return (String)get_Value(COLUMNNAME_UPC); } /** Set Partner Category. @param VendorCategory Product Category of the Business Partner */ public void setVendorCategory (String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } /** Get Partner Category. @return Product Category of the Business Partner */ public String getVendorCategory () { return (String)get_Value(COLUMNNAME_VendorCategory); }
/** Set Partner Product Key. @param VendorProductNo Product Key of the Business Partner */ public void setVendorProductNo (String VendorProductNo) { set_Value (COLUMNNAME_VendorProductNo, VendorProductNo); } /** Get Partner Product Key. @return Product Key of the Business Partner */ public String getVendorProductNo () { return (String)get_Value(COLUMNNAME_VendorProductNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_PO.java
1
请完成以下Java代码
public class DefaultHistoryTaskManager implements InternalHistoryTaskManager { protected ProcessEngineConfigurationImpl processEngineConfiguration; public DefaultHistoryTaskManager(ProcessEngineConfigurationImpl processEngineConfiguration) { this.processEngineConfiguration = processEngineConfiguration; } @Override public void recordTaskInfoChange(TaskEntity taskEntity, Date changeTime) { getActivityInstanceEntityManager().recordTaskInfoChange(taskEntity, changeTime); } @Override public void recordTaskCreated(TaskEntity taskEntity) {
CommandContextUtil.getHistoryManager().recordTaskCreated(taskEntity, null); } @Override public void recordHistoryUserTaskLog(HistoricTaskLogEntryBuilder taskLogEntryBuilder) { CommandContextUtil.getHistoryManager().recordHistoricUserTaskLogEntry(taskLogEntryBuilder); } @Override public void deleteHistoryUserTaskLog(long logNumber) { CommandContextUtil.getHistoryManager().deleteHistoryUserTaskLog(logNumber); } protected ActivityInstanceEntityManager getActivityInstanceEntityManager() { return processEngineConfiguration.getActivityInstanceEntityManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\history\DefaultHistoryTaskManager.java
1
请完成以下Java代码
public BigDecimal getAvailableAmount(final PaymentId paymentId) { Adempiere.assertUnitTestMode(); final I_C_Payment payment = getById(paymentId); return payment.getPayAmt(); } @Override public BigDecimal getAllocatedAmt(final PaymentId paymentId) { final I_C_Payment payment = getById(paymentId); return getAllocatedAmt(payment); } @Override public BigDecimal getAllocatedAmt(final I_C_Payment payment) { Adempiere.assertUnitTestMode(); BigDecimal sum = BigDecimal.ZERO; for (final I_C_AllocationLine line : retrieveAllocationLines(payment)) { final I_C_AllocationHdr ah = line.getC_AllocationHdr(); final BigDecimal lineAmt = line.getAmount(); if (null != ah && ah.getC_Currency_ID() != payment.getC_Currency_ID()) { final BigDecimal lineAmtConv = Services.get(ICurrencyBL.class).convert( lineAmt, // Amt CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID CurrencyId.ofRepoId(payment.getC_Currency_ID()), // CurTo_ID ah.getDateTrx().toInstant(), // ConvDate CurrencyConversionTypeId.ofRepoIdOrNull(payment.getC_ConversionType_ID()),
ClientId.ofRepoId(line.getAD_Client_ID()), OrgId.ofRepoId(line.getAD_Org_ID())); sum = sum.add(lineAmtConv); } else { sum = sum.add(lineAmt); } } return sum; } @Override public void updateDiscountAndPayment(final I_C_Payment payment, final int c_Invoice_ID, final I_C_DocType c_DocType) { Adempiere.assertUnitTestMode(); throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PlainPaymentDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class PaymentToAllocate { @NonNull PaymentId paymentId; @NonNull ClientAndOrgId clientAndOrgId; @NonNull String documentNo; @NonNull BPartnerId bpartnerId; @NonNull LocalDate dateTrx;
@NonNull LocalDate dateAcct; @NonNull PaymentAmtMultiplier paymentAmtMultiplier; @NonNull Amount payAmt; @NonNull Amount openAmt; @NonNull PaymentDirection paymentDirection; @NonNull PaymentCurrencyContext paymentCurrencyContext; }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\PaymentToAllocate.java
2
请完成以下Java代码
public ManufacturingJob withCurrentScaleDevice(@Nullable final DeviceId currentScaleDeviceId) { return !DeviceId.equals(this.currentScaleDeviceId, currentScaleDeviceId) ? toBuilder().currentScaleDeviceId(currentScaleDeviceId).build() : this; } @NonNull public LocalDate getDateStartScheduleAsLocalDate() { return dateStartSchedule.toLocalDate(); } @NonNull public ManufacturingJob withChangedRawMaterialIssue(@NonNull final UnaryOperator<RawMaterialsIssue> mapper) {
final ImmutableList<ManufacturingJobActivity> updatedActivities = activities .stream() .map(activity -> activity.withChangedRawMaterialsIssue(mapper)) .collect(ImmutableList.toImmutableList()); return withActivities(updatedActivities); } public Stream<RawMaterialsIssueLine> streamRawMaterialsIssueLines() { return activities.stream() .filter(ManufacturingJobActivity::isRawMaterialsIssue) .map(ManufacturingJobActivity::getRawMaterialsIssue) .filter(Objects::nonNull) .flatMap(rawMaterialsIssue -> rawMaterialsIssue.getLines().stream()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJob.java
1
请在Spring Boot框架中完成以下Java代码
public class MessageController { @MessageMapping("MyDestination") public Mono<String> message(Mono<String> input) { return input.doOnNext(msg -> System.out.println("Request is:" + msg + ",Request!")) .map(msg -> msg + ",Response!"); } @MessageMapping("Counter") public Flux<String> Counter() { return Flux.range(1, 10) .map(i -> "Count is: " + i); } @MessageMapping("Warning") public Mono<Void> Warning(Mono<String> error) { error.doOnNext(e -> System.out.println("warning is :" + e)) .subscribe(); return Mono.empty(); }
@MessageMapping("channel") public Flux<String> channel(Flux<String> input) { return input.doOnNext(i -> { System.out.println("Received message is : " + i); }) .map(m -> m.toUpperCase()) .doOnNext(r -> { System.out.println("RESPONSE IS :" + r); }); } }
repos\tutorials-master\spring-reactive-modules\spring-6-rsocket\src\main\java\com\baeldung\rsocket\responder\MessageController.java
2
请完成以下Java代码
public class MethodsToInitializeLinkedList { /** * Initialize an Empty List */ public void initializeEmptyList() { LinkedList<String> linkedList=new LinkedList<String>(); linkedList.addFirst("one"); linkedList.add("two"); linkedList.add("three"); System.out.println(linkedList); }
/** * Initialize a List from a Collection */ public void initializeListFromCollection() { ArrayList<Integer> arrayList=new ArrayList<Integer>(3); arrayList.add(Integer.valueOf(1)); arrayList.add(Integer.valueOf(2)); arrayList.add(Integer.valueOf(3)); LinkedList<Integer> linkedList=new LinkedList<Integer>(arrayList); System.out.println(linkedList); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-2\src\main\java\com\baeldung\linkedlist\MethodsToInitializeLinkedList.java
1
请在Spring Boot框架中完成以下Java代码
public String getServiceValue() { return "LocalFileSyncProducts"; } @Override public String getExternalSystemTypeCode() { return PCM_SYSTEM_NAME; } @Override public String getEnableCommand() { return START_PRODUCT_SYNC_LOCAL_FILE_ROUTE; }
@Override public String getDisableCommand() { return STOP_PRODUCT_SYNC_LOCAL_FILE_ROUTE; } @NonNull public String getStartProductRouteId() { return getExternalSystemTypeCode() + "-" + getEnableCommand(); } @NonNull public String getStopProductRouteId() { return getExternalSystemTypeCode() + "-" + getDisableCommand(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\product\LocalFileProductSyncServicePCMRouteBuilder.java
2
请完成以下Java代码
public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Salary salary = new Salary(); String salaryValue = rs.getString(position); salary.setAmount(Long.parseLong(salaryValue.split(" ")[1])); salary.setCurrency(salaryValue.split(" ")[0]); return salary; } @Override public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) st.setNull(index, Types.VARCHAR); else { Long salaryValue = SalaryCurrencyConvertor.convert(value.getAmount(), value.getCurrency(), localCurrency); st.setString(index, value.getCurrency() + " " + salaryValue); } } @Override public Salary deepCopy(Salary value) { if (Objects.isNull(value)) return null; Salary newSal = new Salary(); newSal.setAmount(value.getAmount()); newSal.setCurrency(value.getCurrency()); return newSal; } @Override public boolean isMutable() { return true; } @Override
public Serializable disassemble(Salary value) { return deepCopy(value); } @Override public Salary assemble(Serializable cached, Object owner) { return deepCopy((Salary) cached); } @Override public Salary replace(Salary detached, Salary managed, Object owner) { return detached; } @Override public void setParameterValues(Properties parameters) { this.localCurrency = parameters.getProperty("currency"); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\SalaryType.java
1
请完成以下Java代码
public final class WidgetsBundleWidgetEntity implements ToData<WidgetsBundleWidget> { @Id @Column(name = "widgets_bundle_id", columnDefinition = "uuid") private UUID widgetsBundleId; @Id @Column(name = "widget_type_id", columnDefinition = "uuid") private UUID widgetTypeId; @Column(name = WIDGET_TYPE_ORDER_PROPERTY) private int widgetTypeOrder; public WidgetsBundleWidgetEntity() { super(); } public WidgetsBundleWidgetEntity(WidgetsBundleWidget widgetsBundleWidget) { widgetsBundleId = widgetsBundleWidget.getWidgetsBundleId().getId(); widgetTypeId = widgetsBundleWidget.getWidgetTypeId().getId(); widgetTypeOrder = widgetsBundleWidget.getWidgetTypeOrder(); }
public WidgetsBundleWidgetEntity(UUID widgetsBundleId, UUID widgetTypeId, int widgetTypeOrder) { this.widgetsBundleId = widgetsBundleId; this.widgetTypeId = widgetTypeId; this.widgetTypeOrder = widgetTypeOrder; } @Override public WidgetsBundleWidget toData() { WidgetsBundleWidget result = new WidgetsBundleWidget(); result.setWidgetsBundleId(new WidgetsBundleId(widgetsBundleId)); result.setWidgetTypeId(new WidgetTypeId(widgetTypeId)); result.setWidgetTypeOrder(widgetTypeOrder); return result; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\WidgetsBundleWidgetEntity.java
1
请完成以下Java代码
public static SOTrx ofBoolean(@Nullable final Boolean isSOTrx) { return ofNullableBoolean(isSOTrx); } @Nullable public static SOTrx ofNullableBoolean(@Nullable final Boolean isSOTrx) { return isSOTrx != null ? ofBooleanNotNull(isSOTrx) : null; } @NonNull public static SOTrx ofBooleanNotNull(@NonNull final Boolean isSOTrx) { return isSOTrx ? SALES : PURCHASE; } public static Optional<SOTrx> optionalOfBoolean(@Nullable final Boolean isSOTrx) { return isSOTrx != null ? Optional.of(ofBooleanNotNull(isSOTrx)) : Optional.empty(); } public boolean toBoolean() { return isSales(); } public static boolean toBoolean(final SOTrx soTrx) { if (soTrx == null) { return false; } return soTrx.toBoolean(); } public boolean isSales() {
return this == SALES; } public boolean isPurchase() { return this == PURCHASE; } /** * @return true if AP (Account Payable), aka Purchase */ public boolean isAP() {return isPurchase();} public SOTrx invert() { return isSales() ? PURCHASE : SALES; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\lang\SOTrx.java
1
请完成以下Java代码
public WorkingTime estimateWorkingTimePerOneUnit(final PPRoutingActivity activity) { final I_C_UOM uomEach = Services.get(IUOMDAO.class).getEachUOM(); return estimateWorkingTime(activity, Quantity.of(1, uomEach)); } private WorkingTime estimateWorkingTime(@NonNull final PPRoutingActivity activity, @NonNull final Quantity qty) { return WorkingTime.builder() .durationPerOneUnit(activity.getDurationPerOneUnit()) .unitsPerCycle(activity.getUnitsPerCycle()) .qty(qty) .activityTimeUnit(activity.getDurationUnit()) .build(); } @Override public Duration calculateDuration(@NonNull final PPRoutingActivity activity) { final Duration setupTime = activity.getSetupTime(); final Duration duration = estimateWorkingTimePerOneUnit(activity).getDuration(); final BigDecimal qtyPerBatch = activity.getQtyPerBatch(); final Duration setupTimePerBatch = Duration.ofNanos((long)(setupTime.toNanos() / qtyPerBatch.doubleValue())); return setupTimePerBatch.plus(duration); } @Override public int calculateDurationDays(final PPRoutingId routingId, @Nullable final ResourceId plantId, final BigDecimal qty) { if (plantId == null) { return 0; } Duration durationTotal = Duration.ZERO; final PPRouting routing = Services.get(IPPRoutingRepository.class).getById(routingId); final int intQty = qty.setScale(0, RoundingMode.UP).intValueExact(); for (final PPRoutingActivity activity : routing.getActivities()) { // Qty independent times: durationTotal = durationTotal .plus(activity.getQueuingTime()) .plus(activity.getSetupTime())
.plus(activity.getWaitingTime()) .plus(activity.getMovingTime()); // Get OverlapUnits - number of units that must be completed before they are moved the next activity final int overlapUnits = Integer.max(activity.getOverlapUnits(), 0); final int batchUnits = Integer.max(intQty - overlapUnits, 0); final Duration durationBeforeOverlap = activity.getDurationPerOneUnit().multipliedBy(batchUnits); durationTotal = durationTotal.plus(durationBeforeOverlap); } // final IResourceProductService resourceProductService = Services.get(IResourceProductService.class); final ResourceType resourceType = resourceProductService.getResourceTypeByResourceId(plantId); final BigDecimal availableDayTimeInHours = BigDecimal.valueOf(resourceType.getTimeSlotInHours()); final int availableDays = resourceType.getAvailableDaysPerWeek(); // Weekly Factor final BigDecimal weeklyFactor = BigDecimal.valueOf(7).divide(BigDecimal.valueOf(availableDays), 8, RoundingMode.UP); return BigDecimal.valueOf(durationTotal.toHours()) .multiply(weeklyFactor) .divide(availableDayTimeInHours, 0, RoundingMode.UP) .intValueExact(); } @Override public Duration getResourceBaseValue(@NonNull final PPRoutingActivity activity) { return calculateDuration(activity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\impl\DefaultRoutingServiceImpl.java
1
请完成以下Java代码
public ResponseEntity<JsonResponseUpsert> putProductPriceByPriceListIdentifier( @ApiParam(required = true, value = PRICE_LIST_IDENTIFIER) @PathVariable("priceListIdentifier") @NonNull final String priceListIdentifier, @RequestBody @NonNull final JsonRequestProductPriceUpsert request) { final JsonResponseUpsert responseUpsert = productPriceRestService.upsertProductPricesForPriceList(priceListIdentifier, request); return ResponseEntity.ok().body(responseUpsert); } @ApiOperation("Search product prices by a given `JsonProductPriceSearchRequest`") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully processed the request"), @ApiResponse(code = 401, message = "You are not authorized to consume this resource"), @ApiResponse(code = 403, message = "Accessing a related resource is forbidden"), @ApiResponse(code = 422, message = "The request body could not be processed") }) @PostMapping("{orgCode}/product/search")
public ResponseEntity<?> productPriceSearch( @PathVariable("orgCode") @Nullable final String orgCode, @RequestBody @NonNull final JsonRequestProductPriceQuery request) { try { final JsonResponseProductPriceQuery result = productPriceRestService.productPriceSearch(request, orgCode); return ResponseEntity.ok(result); } catch (final Exception ex) { return ResponseEntity .status(HttpStatus.UNPROCESSABLE_ENTITY) .body(ex.getMessage()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\pricing\PricesRestController.java
1
请完成以下Java代码
public class AExport { private static final Logger log = LogManager.getLogger(AExport.class); private int m_WindowNo = 0; public AExport(final APanel parent) { m_WindowNo = parent.getWindowNo(); // final JFileChooser chooser = new JFileChooser(); final Set<String> fileExtensions = ExcelFormats.getFileExtensionsDefaultFirst(); for(String fileExtension : fileExtensions) { final String formatName = ExcelFormats.getFormatByFileExtension(fileExtension).getName(); final ExtensionFileFilter filter = new ExtensionFileFilter(fileExtension, fileExtension + " - " + formatName); chooser.addChoosableFileFilter(filter); } if (chooser.showSaveDialog(parent) != JFileChooser.APPROVE_OPTION) { return; } // Create File File outFile = ExtensionFileFilter.getFile(chooser.getSelectedFile(), chooser.getFileFilter()); try { outFile.createNewFile(); } catch (IOException e) { log.error("", e); ADialog.error(m_WindowNo, parent, "FileCannotCreate", e.getLocalizedMessage()); return; } final String fileExtension = Files.getFileExtension(outFile.getPath()); parent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try
{ if(fileExtensions.contains(fileExtension)) { createXLS(outFile, parent.getCurrentTab()); } else { ADialog.error(m_WindowNo, parent, "FileInvalidExtension"); } } catch (Exception e) { ADialog.error(m_WindowNo, parent, "Error", e.getLocalizedMessage()); if (LogManager.isLevelFinest()) e.printStackTrace(); } finally { parent.setCursor(Cursor.getDefaultCursor()); } } private void createXLS(@NonNull final File outFile, @NonNull final GridTab tab) { GridTabExcelExporter.builder() .excelFormat(ExcelFormats.getFormatByFile(outFile)) .tab(tab) .build() .exportToFile(outFile); Env.startBrowser(outFile); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AExport.java
1
请完成以下Java代码
public class PersonWithAddress { private Integer id; private String name; private List<Address> address; public PersonWithAddress(Integer id, String name, List<Address> address) { this.id = id; this.name = name; this.address = address; } public Integer getId() { return id; } public String getName() { return name;
} public void setId(Integer id) { this.id = id; } public void setName(String name) { this.name = name; } public List<Address> getAddress() { return address; } public void setAddress(List<Address> address) { this.address = address; } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\javers\PersonWithAddress.java
1
请完成以下Java代码
public String toString() { return "Book{" + "id=" + id + ", title='" + title + '\'' + ", price=" + price + ", publishDate=" + publishDate + '}'; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public BigDecimal getPrice() {
return price; } public void setPrice(BigDecimal price) { this.price = price; } public LocalDate getPublishDate() { return publishDate; } public void setPublishDate(LocalDate publishDate) { this.publishDate = publishDate; } }
repos\spring-boot-master\spring-boot-commandlinerunner\src\main\java\com\mkyong\book\Book.java
1
请完成以下Java代码
public Long getOneMinuteBlock() { return oneMinuteBlock; } public void setOneMinuteBlock(Long oneMinuteBlock) { this.oneMinuteBlock = oneMinuteBlock; } public Long getOneMinuteException() { return oneMinuteException; } public void setOneMinuteException(Long oneMinuteException) { this.oneMinuteException = oneMinuteException; } public Long getOneMinuteTotal() { return oneMinuteTotal; } public void setOneMinuteTotal(Long oneMinuteTotal) {
this.oneMinuteTotal = oneMinuteTotal; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public List<ResourceTreeNode> getChildren() { return children; } public void setChildren(List<ResourceTreeNode> children) { this.children = children; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\ResourceTreeNode.java
1
请完成以下Java代码
public int getC_Phonecall_Schema_Version_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Phonecall_Schema_Version_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Anruf Planung Version Position. @param C_Phonecall_Schema_Version_Line_ID Anruf Planung Version Position */ @Override public void setC_Phonecall_Schema_Version_Line_ID (int C_Phonecall_Schema_Version_Line_ID) { if (C_Phonecall_Schema_Version_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Phonecall_Schema_Version_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Phonecall_Schema_Version_Line_ID, Integer.valueOf(C_Phonecall_Schema_Version_Line_ID)); } /** Get Anruf Planung Version Position. @return Anruf Planung Version Position */ @Override public int getC_Phonecall_Schema_Version_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Phonecall_Schema_Version_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Erreichbar bis. @param PhonecallTimeMax Erreichbar bis */ @Override public void setPhonecallTimeMax (java.sql.Timestamp PhonecallTimeMax) { set_Value (COLUMNNAME_PhonecallTimeMax, PhonecallTimeMax); } /** Get Erreichbar bis. @return Erreichbar bis */ @Override public java.sql.Timestamp getPhonecallTimeMax () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMax); }
/** Set Erreichbar von. @param PhonecallTimeMin Erreichbar von */ @Override public void setPhonecallTimeMin (java.sql.Timestamp PhonecallTimeMin) { set_Value (COLUMNNAME_PhonecallTimeMin, PhonecallTimeMin); } /** Get Erreichbar von. @return Erreichbar von */ @Override public java.sql.Timestamp getPhonecallTimeMin () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMin); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phonecall_Schema_Version_Line.java
1
请完成以下Java代码
public String getSessionId() { return this.sessionId; } /** * Returns the client identifier the ID Token was issued to. * @return the client identifier */ @Nullable public String getClientId() { return this.clientId; } /** * Returns the URI which the Client is requesting that the End-User's User Agent be * redirected to after a logout has been performed. * @return the URI which the Client is requesting that the End-User's User Agent be * redirected to after a logout has been performed
*/ @Nullable public String getPostLogoutRedirectUri() { return this.postLogoutRedirectUri; } /** * Returns the opaque value used by the Client to maintain state between the logout * request and the callback to the {@link #getPostLogoutRedirectUri()}. * @return the opaque value used by the Client to maintain state between the logout * request and the callback to the {@link #getPostLogoutRedirectUri()} */ @Nullable public String getState() { return this.state; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcLogoutAuthenticationToken.java
1
请完成以下Java代码
public class DelegateExpressionHttpHandler implements HttpRequestHandler, HttpResponseHandler { protected Expression expression; protected final List<FieldDeclaration> fieldDeclarations; public DelegateExpressionHttpHandler(Expression expression, List<FieldDeclaration> fieldDeclarations) { this.expression = expression; this.fieldDeclarations = fieldDeclarations; } @Override public void handleHttpRequest(VariableContainer execution, HttpRequest httpRequest, FlowableHttpClient client) { Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expression, execution, fieldDeclarations); if (delegate instanceof HttpRequestHandler) { CommandContextUtil.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation( new HttpRequestHandlerInvocation((HttpRequestHandler) delegate, execution, httpRequest, client)); } else { throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + HttpRequestHandler.class); } }
@Override public void handleHttpResponse(VariableContainer execution, HttpResponse httpResponse) { Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expression, execution, fieldDeclarations); if (delegate instanceof HttpResponseHandler) { CommandContextUtil.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation( new HttpResponseHandlerInvocation((HttpResponseHandler) delegate, execution, httpResponse)); } else { throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + HttpResponseHandler.class); } } /** * returns the expression text for this execution listener. Comes in handy if you want to check which listeners you already have. */ public String getExpressionText() { return expression.getExpressionText(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\http\handler\DelegateExpressionHttpHandler.java
1
请完成以下Java代码
public String toString() { return name; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { b.append(bindings != null && bindings.isFunctionBound(index) ? "<fn>" : name); params.appendStructure(b, bindings); } public int getIndex() { return index; } public String getName() { return name; } public boolean isVarArgs() { return varargs; }
public int getParamCount() { return params.getCardinality(); } protected AstNode getParam(int i) { return params.getChild(i); } public int getCardinality() { return 1; } public AstNode getChild(int i) { return i == 0 ? params : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstFunction.java
1
请在Spring Boot框架中完成以下Java代码
public class Cart { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @ManyToOne @JoinColumn(name="customer_id") private User customer; // @ManyToMany // @JoinTable( // joinColumns = @JoinColumn(name = "cart_id"), // inverseJoinColumns = @JoinColumn(name = "product_id") // ) // private List<Product> products; public Cart() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public User getCustomer() { return customer; } public void setCustomer(User customer) { this.customer = customer; } // public List<Product> getProducts() {
// return products; // } // public List<Product> getProductsByUser(int customer_id ) { // List<Product> userProducts = new ArrayList<Product>(); // for (Product product : products) { // if (product.getCustomer().getId() == customer_id) { // userProducts.add(product); // } // } // return userProducts; // } // public void setProducts(List<Product> products) { // this.products = products; // } // public void addProduct(Product product) { // products.add(product); // } // // public void removeProduct(Product product) { // products.remove(product); // } }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\Cart.java
2
请完成以下Java代码
public IAttributeStorage getParentAttributeStorage() { return NullAttributeStorage.instance; } /** * Always returns an empty collection. */ @Override public final List<IAttributeStorage> getChildAttributeStorages(boolean loadIfNeeded_IGNORED) { return ImmutableList.of(); } @Override protected void toString(final ToStringHelper stringHelper) { stringHelper .add("id", id) .add("asi", asi); } @Override protected List<IAttributeValue> loadAttributeValues() { final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class); final ImmutableList.Builder<IAttributeValue> result = ImmutableList.builder(); final List<I_M_AttributeInstance> attributeInstances = asiBL.getAttributeInstances(asi); for (final I_M_AttributeInstance attributeInstance : attributeInstances) { final IAttributeValue attributeValue = new AIAttributeValue(this, attributeInstance); result.add(attributeValue); } return result.build(); } @Override protected List<IAttributeValue> generateAndGetInitialAttributes(final IAttributeValueContext attributesCtx, final Map<AttributeId, Object> defaultAttributesValue) { throw new UnsupportedOperationException("Generating initial attributes not supported for " + this); } @Override public void updateHUTrxAttribute(final MutableHUTransactionAttribute huTrxAttribute, final IAttributeValue fromAttributeValue) { huTrxAttribute.setReferencedObject(asi); } /** * Method not supported. * * @throws UnsupportedOperationException */ @Override protected void addChildAttributeStorage(final IAttributeStorage childAttributeStorage) {
throw new UnsupportedOperationException("Child attribute storages are not supported for " + this); } /** * Method not supported. * * @throws UnsupportedOperationException */ @Override protected IAttributeStorage removeChildAttributeStorage(final IAttributeStorage childAttributeStorage) { throw new UnsupportedOperationException("Child attribute storages are not supported for " + this); } @Override public void saveChangesIfNeeded() { throw new UnsupportedOperationException(); } @Override public void setSaveOnChange(boolean saveOnChange) { throw new UnsupportedOperationException(); } @Override public UOMType getQtyUOMTypeOrNull() { // ASI attribute storages does not support Qty Storage return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\ASIAttributeStorage.java
1
请完成以下Java代码
public GatewayFilter apply(Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { return chain.filter(exchange) .then(Mono.fromRunnable(() -> dedupe(exchange.getResponse().getHeaders(), config))); } @Override public String toString() { String name = config.getName(); return filterToStringCreator(DedupeResponseHeaderGatewayFilterFactory.this) .append(name != null ? name : "", config.getStrategy()) .toString(); } }; } public enum Strategy { /** * Default: Retain the first value only. */ RETAIN_FIRST, /** * Retain the last value only. */ RETAIN_LAST, /** * Retain all unique values in the order of their first encounter. */ RETAIN_UNIQUE } void dedupe(HttpHeaders headers, Config config) { String names = config.getName(); Strategy strategy = config.getStrategy(); if (headers == null || names == null || strategy == null) { return; } for (String name : names.split(" ")) { dedupe(headers, name.trim(), strategy); } } private void dedupe(HttpHeaders headers, String name, Strategy strategy) { List<String> values = headers.get(name); if (values == null || values.size() <= 1) { return; } switch (strategy) { case RETAIN_FIRST: headers.set(name, values.get(0)); break; case RETAIN_LAST:
headers.set(name, values.get(values.size() - 1)); break; case RETAIN_UNIQUE: headers.put(name, new ArrayList<>(new LinkedHashSet<>(values))); break; default: break; } } public static class Config extends AbstractGatewayFilterFactory.NameConfig { private Strategy strategy = Strategy.RETAIN_FIRST; public Strategy getStrategy() { return strategy; } public Config setStrategy(Strategy strategy) { this.strategy = strategy; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\DedupeResponseHeaderGatewayFilterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public void process(@NonNull final Exchange exchange) { final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class); final String content = updatePluFile(context); final DispatchMessageRequest request = DispatchMessageRequest.builder() .destinationDetails(context.getDestinationDetails()) .payload(content) .build(); exchange.getIn().setBody(request, DispatchMessageRequest.class); } @NonNull private String updatePluFile(@NonNull final ExportPPOrderRouteContext context) { final String productBaseFolderName = context.getPluTemplateFileBaseFolderName(); final JsonExternalSystemLeichMehlConfigProductMapping mapping = context.getProductMapping(); try { final Path filePath = getPluFilePath(productBaseFolderName, mapping.getPluFile()); final Document pluDocument = XMLUtil.readFromPath(filePath); final JsonPluFileAudit jsonPluFileAudit = updateDocument(pluDocument, filePath, context); final String fileContentWithoutXMLDeclaration = XMLUtil.toString(pluDocument); context.setJsonPluFileAudit(jsonPluFileAudit); context.setPluFileXmlContent(addXMLDeclarationIfNeeded(fileContentWithoutXMLDeclaration)); context.setPluTemplateFilename(filePath.getFileName().toString()); return fileContentWithoutXMLDeclaration;
} catch (final Exception e) { throw new RuntimeCamelException(e); } } @NonNull private JsonPluFileAudit updateDocument( @NonNull final Document pluDocument, @NonNull final Path filepath, @NonNull final ExportPPOrderRouteContext context) throws TransformerException { final FileUpdater fileUpdater = FileUpdater.builder() .fileName(filepath.getFileName().toString()) .document(pluDocument) .context(context) .processLogger(processLogger) .build(); return fileUpdater.updateDocument(); } @NonNull private static Path getPluFilePath(@NonNull final String productBaseFolderName, @NonNull final String pluFilepath) { return Paths.get(productBaseFolderName, FileUtil.normalizeAndValidateFilePath(pluFilepath)); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\processor\ReadPluFileProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public PPOrderQuantities getQuantities(@NonNull final I_PP_Order order) {return ppOrderBOMBL.getQuantities(order);} public OrderBOMLineQuantities getQuantities(@NonNull final I_PP_Order_BOMLine orderBOMLine) {return ppOrderBOMBL.getQuantities(orderBOMLine);} public ImmutableListMultimap<PPOrderBOMLineId, PPOrderIssueSchedule> getIssueSchedules(@NonNull final PPOrderId ppOrderId) { return Multimaps.index(ppOrderIssueScheduleService.getByOrderId(ppOrderId), PPOrderIssueSchedule::getPpOrderBOMLineId); } public ImmutableAttributeSet getImmutableAttributeSet(final AttributeSetInstanceId asiId) { return asiBL.getImmutableAttributeSetById(asiId); } public Optional<HuId> getHuIdByQRCodeIfExists(@NonNull final HUQRCode qrCode) { return huQRCodeService.getHuIdByQRCodeIfExists(qrCode); } public void assignQRCodeForReceiptHU(@NonNull final HUQRCode qrCode, @NonNull final HuId huId) { final boolean ensureSingleAssignment = true; huQRCodeService.assign(qrCode, huId, ensureSingleAssignment); } public HUQRCode getFirstQRCodeByHuId(@NonNull final HuId huId) { return huQRCodeService.getFirstQRCodeByHuId(huId); } public Quantity getHUCapacity( @NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final I_C_UOM uom) { final I_M_HU hu = handlingUnitsBL.getById(huId); return handlingUnitsBL .getStorageFactory() .getStorage(hu) .getQuantity(productId, uom); } @NonNull public ValidateLocatorInfo getValidateSourceLocatorInfo(final @NonNull PPOrderId ppOrderId)
{ final ImmutableList<LocatorInfo> sourceLocatorList = getSourceLocatorIds(ppOrderId) .stream() .map(locatorId -> { final String caption = getLocatorName(locatorId); return LocatorInfo.builder() .id(locatorId) .caption(caption) .qrCode(LocatorQRCode.builder() .locatorId(locatorId) .caption(caption) .build()) .build(); }) .collect(ImmutableList.toImmutableList()); return ValidateLocatorInfo.ofSourceLocatorList(sourceLocatorList); } @NonNull public Optional<UomId> getCatchWeightUOMId(@NonNull final ProductId productId) { return productBL.getCatchUOMId(productId); } @NonNull private ImmutableSet<LocatorId> getSourceLocatorIds(@NonNull final PPOrderId ppOrderId) { final ImmutableSet<HuId> huIds = sourceHUService.getSourceHUIds(ppOrderId); return handlingUnitsBL.getLocatorIds(huIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaverSupportingServices.java
2
请在Spring Boot框架中完成以下Java代码
public boolean insertExternalWorkerJobEntity(ExternalWorkerJobEntity jobEntity) { return doInsert(jobEntity, true); } @Override public void insert(ExternalWorkerJobEntity jobEntity, boolean fireCreateEvent) { doInsert(jobEntity, fireCreateEvent); } protected boolean doInsert(ExternalWorkerJobEntity jobEntity, boolean fireCreateEvent) { if (serviceConfiguration.getInternalJobManager() != null) { boolean handledJob = serviceConfiguration.getInternalJobManager().handleJobInsert(jobEntity); if (!handledJob) { return false; } } jobEntity.setCreateTime(getClock().getCurrentTime()); if (jobEntity.getCorrelationId() == null) { jobEntity.setCorrelationId(serviceConfiguration.getIdGenerator().getNextId()); } super.insert(jobEntity, fireCreateEvent); return true; } @Override public ExternalWorkerJobEntity findJobByCorrelationId(String correlationId) { return dataManager.findJobByCorrelationId(correlationId); } @Override public List<ExternalWorkerJobEntity> findJobsByScopeIdAndSubScopeId(String scopeId, String subScopeId) { return dataManager.findJobsByScopeIdAndSubScopeId(scopeId, subScopeId); } @Override public List<ExternalWorkerJobEntity> findJobsByWorkerId(String workerId) { return dataManager.findJobsByWorkerId(workerId); } @Override public List<ExternalWorkerJobEntity> findJobsByWorkerIdAndTenantId(String workerId, String tenantId) { return dataManager.findJobsByWorkerIdAndTenantId(workerId, tenantId); }
@Override public List<ExternalWorkerJob> findJobsByQueryCriteria(ExternalWorkerJobQueryImpl jobQuery) { return dataManager.findJobsByQueryCriteria(jobQuery); } @Override public long findJobCountByQueryCriteria(ExternalWorkerJobQueryImpl jobQuery) { return dataManager.findJobCountByQueryCriteria(jobQuery); } @Override public List<ExternalWorkerJobEntity> findExternalJobsToExecute(ExternalWorkerJobAcquireBuilderImpl builder, int numberOfJobs) { return dataManager.findExternalJobsToExecute(builder, numberOfJobs); } @Override public void delete(ExternalWorkerJobEntity entity, boolean fireDeleteEvent) { deleteByteArrayRef(entity.getExceptionByteArrayRef()); deleteByteArrayRef(entity.getCustomValuesByteArrayRef()); if (serviceConfiguration.getInternalJobManager() != null) { serviceConfiguration.getInternalJobManager().handleJobDelete(entity); } super.delete(entity, fireDeleteEvent); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\ExternalWorkerJobEntityManagerImpl.java
2
请完成以下Java代码
public String getEditorSourceValueId() { return editorSourceValueId; } public void setEditorSourceValueId(String editorSourceValueId) { this.editorSourceValueId = editorSourceValueId; } public String getEditorSourceExtraValueId() { return editorSourceExtraValueId; } public void setEditorSourceExtraValueId(String editorSourceExtraValueId) { this.editorSourceExtraValueId = editorSourceExtraValueId; } @Override public int getRevision() { return revision; } @Override public int getRevisionNext() { return revision + 1; } @Override public void setRevision(int revision) { this.revision = revision; }
@Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public boolean hasEditorSource() { return this.editorSourceValueId != null; } @Override public boolean hasEditorSourceExtra() { return this.editorSourceExtraValueId != null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreController { private final BookstoreService bookstoreService; public BookstoreController(BookstoreService bookstoreService) { this.bookstoreService = bookstoreService; } @GetMapping("/page/{page}/{size}") public Page<Author> fetchPageOfAuthorsWithBooksByGenre( @PathVariable int page, @PathVariable int size) { return bookstoreService.fetchPageOfAuthorsWithBooksByGenre(page, size); } @GetMapping("/slice/{page}/{size}") public Slice<Author> fetchSliceOfAuthorsWithBooksByGenre( @PathVariable int page, @PathVariable int size) { return bookstoreService.fetchSliceOfAuthorsWithBooksByGenre(page, size); } @GetMapping("/list/{page}/{size}") public List<Author> fetchListOfAuthorsWithBooksByGenre( @PathVariable int page, @PathVariable int size) {
return bookstoreService.fetchListOfAuthorsWithBooksByGenre(page, size); } @GetMapping("/page/eg/{page}/{size}") public Page<Author> fetchPageOfAuthorsWithBooksByGenreEntityGraph( @PathVariable int page, @PathVariable int size) { return bookstoreService.fetchPageOfAuthorsWithBooksByGenreEntityGraph(page, size); } @GetMapping("/page/tuple/{page}/{size}") public Page<Author> fetchPageOfAuthorsWithBooksByGenreTuple( @PathVariable int page, @PathVariable int size) { return bookstoreService.fetchPageOfAuthorsWithBooksByGenreTuple(page, size); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootHHH000104\src\main\java\com\bookstore\controller\BookstoreController.java
2
请完成以下Java代码
public String fileUploadForm(Model model) { return "fileDownloadView"; } // Using ResponseEntity<InputStreamResource> @GetMapping("/download1") public ResponseEntity<InputStreamResource> downloadFile1() throws IOException { File file = new File(FILE_PATH); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName()) .contentType(MediaType.APPLICATION_PDF).contentLength(file.length()) .body(resource); } // Using ResponseEntity<ByteArrayResource> @GetMapping("/download2") public ResponseEntity<ByteArrayResource> downloadFile2() throws IOException{ Path path = Paths.get(FILE_PATH); byte[] data = Files.readAllBytes(path); ByteArrayResource resource = new ByteArrayResource(data); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + path.getFileName().toString()) .contentType(MediaType.APPLICATION_PDF).contentLength(data.length) .body(resource); } //Using HttpServeltResponse
@GetMapping("/download3") public void downloadFile3(HttpServletResponse response) throws IOException{ File file = new File(FILE_PATH); response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); } }
repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSourceCode\SpringDownloadFiles\src\main\java\spring\basic\FileDownloadController.java
1
请在Spring Boot框架中完成以下Java代码
public boolean canRead(Type type, @Nullable Class<?> contextClass, @Nullable MediaType mediaType) { return this.smartConverter.canRead(ResolvableType.forType(type), mediaType); } @Override public T read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return this.smartConverter.read(ResolvableType.forType(type), inputMessage, null); } @Override public boolean canWrite(@Nullable Type type, Class<?> clazz, @Nullable MediaType mediaType) { return this.smartConverter.canWrite(ResolvableType.forType(type), clazz, mediaType); } @Override public void write(T t, @Nullable Type type, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { this.smartConverter.write(t, ResolvableType.forType(type), contentType, outputMessage, null); } @Override public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) { return this.smartConverter.canRead(ResolvableType.forClass(clazz), mediaType); } @Override public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) { return this.smartConverter.canWrite(clazz, mediaType); }
@Override public List<MediaType> getSupportedMediaTypes() { return this.smartConverter.getSupportedMediaTypes(); } @Override public T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return this.smartConverter.read(clazz, inputMessage); } @Override public void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { this.smartConverter.write(t, contentType, outputMessage); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\web\server\GenericHttpMessageConverterAdapter.java
2
请完成以下Java代码
public SetRemovalTimeToHistoricProcessInstancesBuilder calculatedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.CALCULATED_REMOVAL_TIME; return this; } @Override public SetRemovalTimeToHistoricProcessInstancesBuilder clearedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.CLEARED_REMOVAL_TIME; return this; } @Override public SetRemovalTimeToHistoricProcessInstancesBuilder hierarchical() { isHierarchical = true; return this; } @Override public SetRemovalTimeToHistoricProcessInstancesBuilder updateInChunks() { updateInChunks = true; return this; } @Override public SetRemovalTimeToHistoricProcessInstancesBuilder chunkSize(int chunkSize) { if (chunkSize > ProcessSetRemovalTimeJobHandler.MAX_CHUNK_SIZE || chunkSize <= 0) { throw new BadUserRequestException(String.format("The value for chunk size should be between 1 and %s", ProcessSetRemovalTimeJobHandler.MAX_CHUNK_SIZE)); } this.chunkSize = chunkSize; return this; } @Override public Batch executeAsync() { return commandExecutor.execute(new SetRemovalTimeToHistoricProcessInstancesCmd(this)); } public HistoricProcessInstanceQuery getQuery() { return query; } public List<String> getIds() { return ids; } public Date getRemovalTime() {
return removalTime; } public Mode getMode() { return mode; } public boolean isHierarchical() { return isHierarchical; } public boolean isUpdateInChunks() { return updateInChunks; } public Integer getChunkSize() { return chunkSize; } public static enum Mode { CALCULATED_REMOVAL_TIME, ABSOLUTE_REMOVAL_TIME, CLEARED_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricProcessInstancesBuilderImpl.java
1
请完成以下Java代码
public int getBatchJobsPerSeed() { return batchJobsPerSeed; } public int getInvocationsPerBatchJob() { return invocationsPerBatchJob; } public String getSeedJobDefinitionId() { return seedJobDefinitionId; } public String getMonitorJobDefinitionId() { return monitorJobDefinitionId; } public String getBatchJobDefinitionId() { return batchJobDefinitionId; } public boolean isSuspended() { return suspended; } public String getTenantId() { return tenantId; } public String getCreateUserId() { return createUserId; } public Date getStartTime() { return startTime; } public void setStartTime(final Date startTime) { this.startTime = startTime; } public Date getExecutionStartTime() { return executionStartTime; } public void setExecutionStartTime(final Date executionStartTime) { this.executionStartTime = executionStartTime;
} public static BatchDto fromBatch(Batch batch) { BatchDto dto = new BatchDto(); dto.id = batch.getId(); dto.type = batch.getType(); dto.totalJobs = batch.getTotalJobs(); dto.jobsCreated = batch.getJobsCreated(); dto.batchJobsPerSeed = batch.getBatchJobsPerSeed(); dto.invocationsPerBatchJob = batch.getInvocationsPerBatchJob(); dto.seedJobDefinitionId = batch.getSeedJobDefinitionId(); dto.monitorJobDefinitionId = batch.getMonitorJobDefinitionId(); dto.batchJobDefinitionId = batch.getBatchJobDefinitionId(); dto.suspended = batch.isSuspended(); dto.tenantId = batch.getTenantId(); dto.createUserId = batch.getCreateUserId(); dto.startTime = batch.getStartTime(); dto.executionStartTime = batch.getExecutionStartTime(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchDto.java
1
请完成以下Java代码
public abstract class AbstractDataPoint implements DataPoint { @Getter private final long ts; @Override public String getStr() { throw new RuntimeException(NOT_SUPPORTED); } @Override public long getLong() { throw new RuntimeException(NOT_SUPPORTED); } @Override public double getDouble() { throw new RuntimeException(NOT_SUPPORTED); } @Override public boolean getBool() { throw new RuntimeException(NOT_SUPPORTED); }
@Override public String getJson() { throw new RuntimeException(NOT_SUPPORTED); } public String toString() { return valueToString(); } @Override public int compareTo(DataPoint dataPoint) { return StringUtils.compareIgnoreCase(valueToString(), dataPoint.valueToString()); } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\data\dp\AbstractDataPoint.java
1
请在Spring Boot框架中完成以下Java代码
public class ESRPaymentInfo implements CustomInvoicePayload { @NonNull String participantNumber; @NonNull String referenceNumber; @NonNull String codingLine; @Nullable String companyName; @Nullable PersonInfo personInfo; @Nullable AddressInfo addressInfo; private ESRPaymentInfo( @NonNull final String participantNumber, @NonNull final String referenceNumber,
@NonNull final String codingLine, @Nullable final String companyName, @Nullable final PersonInfo personInfo, @Nullable final AddressInfo addressInfo) { this.participantNumber = participantNumber; this.referenceNumber = referenceNumber; this.codingLine = codingLine; this.companyName = companyName; this.personInfo = personInfo; this.addressInfo = addressInfo; // take whatever infos we can get, and let the consumers decide what to do with it // assume(isEmpty(companyName) || addressInfo != null, // "If a companyName is given, then an address needs to be given as well; this={}", this); // assume(isEmpty(personInfo) || addressInfo != null, // "If a personInfo is given, then an address needs to be given as well; this={}", this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.invoice_gateway.spi\src\main\java\de\metas\invoice_gateway\spi\esr\model\ESRPaymentInfo.java
2
请在Spring Boot框架中完成以下Java代码
public class HomeProperties { /** * 省份 */ private String province; /** * 城市 */ private String city; /** * 描述 */ private String desc; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDesc() { return desc;
} public void setDesc(String desc) { this.desc = desc; } @Override public String toString() { return "HomeProperties{" + "province='" + province + '\'' + ", city='" + city + '\'' + ", desc='" + desc + '\'' + '}'; } }
repos\springboot-learning-example-master\springboot-properties\src\main\java\org\spring\springboot\property\HomeProperties.java
2
请完成以下Java代码
public void setUsername(String username) { this.username = username; } @Override public String getPassword() { return null; } @Override public boolean isAccountNonExpired() { return true; } @Override
public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\OpenIdConnectUserDetails.java
1
请完成以下Java代码
double cosine(SparseVector vec1, SparseVector vec2) { double norm1 = vec1.norm(); double norm2 = vec2.norm(); double result = 0.0f; if (norm1 == 0 && norm2 == 0) { return result; } else { double prod = inner_product(vec1, vec2); result = prod / (norm1 * norm2); return Double.isNaN(result) ? 0.0f : result; } } // /** // * Calculate the Jaccard coefficient value between vectors. // */
// double jaccard(const Vector &vec1, const Vector &vec2) //{ // double norm1 = vec1.norm(); // double norm2 = vec2.norm(); // double prod = inner_product(vec1, vec2); // double denom = norm1 + norm2 - prod; // double result = 0.0; // if (!denom) // { // return result; // } // else // { // result = prod / denom; // return isnan(result) ? 0.0 : result; // } //} }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\cluster\SparseVector.java
1
请完成以下Java代码
public String getXMLElementName() { return CmmnXmlConstants.ELEMENT_DOCUMENTATION; } @Override public boolean hasChildElements() { return false; } @Override protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { try { String textFormat = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_TEXT_FORMAT); if (StringUtils.isEmpty(textFormat)) { textFormat = "text/plain";
} String documentation = xtr.getElementText(); if (StringUtils.isNotEmpty(documentation)) { conversionHelper.getCurrentCmmnElement().setDocumentation(documentation); conversionHelper.getCurrentCmmnElement().setDocumentationTextFormat(textFormat); } return null; } catch (Exception e) { throw new CmmnXMLException("Error reading documentation element", e); } } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\DocumentationXmlConverter.java
1
请完成以下Java代码
public void setNestedProcessDefinitionId(String nestedProcessDefinitionId) { this.nestedProcessDefinitionId = nestedProcessDefinitionId; } @Override public String getNestedProcessDefinitionId() { return nestedProcessDefinitionId; } public void setNestedProcessInstanceId(String nestedProcessInstanceId) { this.nestedProcessInstanceId = nestedProcessInstanceId; } @Override public String getNestedProcessInstanceId() { return nestedProcessInstanceId; } public void setLinkedProcessInstanceId(String linkedProcessInstanceId) { this.linkedProcessInstanceId = linkedProcessInstanceId; } @Override public String getLinkedProcessInstanceId() { return linkedProcessInstanceId; } public void setLinkedProcessInstanceType(String linkedProcessInstanceType) { this.linkedProcessInstanceType = linkedProcessInstanceType; } @Override public String getLinkedProcessInstanceType() { return linkedProcessInstanceType; } @Override public ProcessEvents getEventType() { return ProcessEvents.PROCESS_STARTED; }
@Override public String toString() { return ( "ProcessStartedEventImpl{" + super.toString() + "nestedProcessDefinitionId='" + nestedProcessDefinitionId + '\'' + ", nestedProcessInstanceId='" + nestedProcessInstanceId + '\'' + ", linkedProcessInstanceId='" + linkedProcessInstanceId + '\'' + ", linkedProcessInstanceType='" + linkedProcessInstanceType + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\impl\ProcessStartedEventImpl.java
1
请在Spring Boot框架中完成以下Java代码
private void addResultAttachements(@NonNull final CreditScore creditScore, @NonNull final TransactionResultId transactionResultId) { final CreditScoreRequestLogData requestLogData = creditScore.getRequestLogData(); if (requestLogData.getRequestData() != null) { final AttachmentEntryCreateRequest requestDataAttachment = AttachmentEntryCreateRequest .fromByteArray( MessageFormat.format("Request_{0}", requestLogData.getCustomerTransactionID()), requestLogData.getRequestData().getBytes(StandardCharsets.UTF_8)); attachmentEntryService.createNewAttachment( TableRecordReference.of(I_CS_Transaction_Result.Table_Name, transactionResultId), requestDataAttachment); } if (requestLogData.getResponseData() != null) { final AttachmentEntryCreateRequest responseDataAttachment = AttachmentEntryCreateRequest
.fromByteArray( MessageFormat.format("Response_{0}", requestLogData.getCustomerTransactionID()), requestLogData.getResponseData().getBytes(StandardCharsets.UTF_8)); attachmentEntryService.createNewAttachment( TableRecordReference.of(I_CS_Transaction_Result.Table_Name, transactionResultId), responseDataAttachment); } } public Optional<TransactionResult> findLastTransactionResult(@NonNull final String paymentRule, @NonNull final BPartnerId bPartnerId) { return transactionResultsRepository .getLastTransactionResult(paymentRule, bPartnerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\base\src\main\java\de\metas\vertical\creditscore\base\spi\service\TransactionResultService.java
2
请在Spring Boot框架中完成以下Java代码
public Scheduler scheduler(Trigger trigger, JobDetail job, SchedulerFactoryBean factory) throws SchedulerException { logger.debug("Getting a handle to the Scheduler"); Scheduler scheduler = factory.getScheduler(); scheduler.scheduleJob(job, trigger); logger.debug("Starting Scheduler threads"); scheduler.start(); return scheduler; } @Bean public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setJobFactory(springBeanJobFactory()); factory.setQuartzProperties(quartzProperties()); return factory; } public Properties quartzProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject(); } @Bean public JobDetail jobDetail() { return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean public Trigger trigger(JobDetail job) { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } }
repos\tutorials-master\spring-quartz\src\main\java\org\baeldung\springquartz\basics\scheduler\QrtzScheduler.java
2
请完成以下Java代码
public String getExecutionId() { return executionId; } public String getId() { return id; } public Date getLockExpirationTime() { return lockExpirationTime; } public Date getCreateTime() { return createTime; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionVersionTag() { return processDefinitionVersionTag; } public String getProcessInstanceId() { return processInstanceId; } public Integer getRetries() { return retries; } public boolean isSuspended() { return suspended; } public String getWorkerId() { return workerId; } public String getTopicName() { return topicName; } public String getTenantId() { return tenantId; } public long getPriority() { return priority; }
public String getBusinessKey() { return businessKey; } public static ExternalTaskDto fromExternalTask(ExternalTask task) { ExternalTaskDto dto = new ExternalTaskDto(); dto.activityId = task.getActivityId(); dto.activityInstanceId = task.getActivityInstanceId(); dto.errorMessage = task.getErrorMessage(); dto.executionId = task.getExecutionId(); dto.id = task.getId(); dto.lockExpirationTime = task.getLockExpirationTime(); dto.createTime = task.getCreateTime(); dto.processDefinitionId = task.getProcessDefinitionId(); dto.processDefinitionKey = task.getProcessDefinitionKey(); dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag(); dto.processInstanceId = task.getProcessInstanceId(); dto.retries = task.getRetries(); dto.suspended = task.isSuspended(); dto.topicName = task.getTopicName(); dto.workerId = task.getWorkerId(); dto.tenantId = task.getTenantId(); dto.priority = task.getPriority(); dto.businessKey = task.getBusinessKey(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\ExternalTaskDto.java
1
请在Spring Boot框架中完成以下Java代码
private String getDefaultPort() { try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) { return String.valueOf(serverSocket.getLocalPort()); } catch (IOException ex) { return RANDOM_PORT; } } private static class EmbeddedLdapServerConfigBean implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @SuppressWarnings("unused") private DefaultSpringSecurityContextSource createEmbeddedContextSource(String suffix) {
int port = getPort(); String providerUrl = "ldap://127.0.0.1:" + port + "/" + suffix; return new DefaultSpringSecurityContextSource(providerUrl); } private int getPort() { if (unboundIdPresent) { UnboundIdContainer unboundIdContainer = this.applicationContext.getBean(UnboundIdContainer.class); return unboundIdContainer.getPort(); } throw new IllegalStateException("Embedded LDAP server is not provided"); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\LdapServerBeanDefinitionParser.java
2
请完成以下Java代码
public class DeleteImportDataProcess extends ViewBasedProcessTemplate implements IProcessPrecondition { private final DataImportService dataImportService = SpringContextHolder.instance.getBean(DataImportService.class); @Param(parameterName = "ImportDeleteMode", mandatory = true) @Getter private ImportDataDeleteMode deleteMode; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getView().size() <= 0) { return ProcessPreconditionsResolution.rejectWithInternalReason("view is empty"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final String importTableName = getTableName(); final ImportDataDeleteMode deleteMode = getDeleteMode(); final String viewSqlWhereClause = getViewSqlWhereClause(DocumentIdsSelection.ALL) .map(SqlViewRowsWhereClause::toSqlString) .orElse(null); final String selectionSqlWhereClause = ImportDataDeleteMode.ONLY_SELECTED.equals(deleteMode) ? getSelectionSqlWhereClause().map(SqlViewRowsWhereClause::toSqlString).orElse(null) : null; final int deletedCount = dataImportService.deleteImportRecords(ImportDataDeleteRequest.builder() .importTableName(importTableName) .mode(deleteMode) .viewSqlWhereClause(viewSqlWhereClause) .selectionSqlWhereClause(selectionSqlWhereClause) .additionalParameters(Params.copyOf(getParameterAsIParams())) .build());
return "@Deleted@ " + deletedCount; } @Override protected void postProcess(final boolean success) { invalidateView(); } private Optional<SqlViewRowsWhereClause> getSelectionSqlWhereClause() { final DocumentIdsSelection rowIds = getSelectedRowIds(); if (rowIds.isEmpty()) { throw new AdempiereException("@NoSelection@"); } return getViewSqlWhereClause(rowIds); } private Optional<SqlViewRowsWhereClause> getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds) { final IView view = getView(); final String importTableName = getTableName(); final SqlViewRowsWhereClause viewRowsWhereClause = view.getSqlWhereClause(rowIds, SqlOptions.usingTableName(importTableName)); return Optional.ofNullable(viewRowsWhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\impexp\DeleteImportDataProcess.java
1
请完成以下Java代码
public class JobUtil { public static JobEntity createJob(ExecutionEntity execution, String jobHandlerType, ProcessEngineConfigurationImpl processEngineConfiguration) { return createJob(execution, execution.getCurrentFlowElement(), jobHandlerType, processEngineConfiguration); } public static JobEntity createJob(ExecutionEntity execution, BaseElement baseElement, String jobHandlerType, ProcessEngineConfigurationImpl processEngineConfiguration) { JobService jobService = processEngineConfiguration.getJobServiceConfiguration().getJobService(); JobEntity job = jobService.createJob(); job.setExecutionId(execution.getId()); job.setProcessInstanceId(execution.getProcessInstanceId()); job.setProcessDefinitionId(execution.getProcessDefinitionId()); job.setElementId(baseElement.getId()); if (baseElement instanceof FlowElement) { job.setElementName(((FlowElement) baseElement).getName()); } job.setJobHandlerType(jobHandlerType); List<ExtensionElement> jobCategoryElements = baseElement.getExtensionElements().get("jobCategory"); if (jobCategoryElements != null && jobCategoryElements.size() > 0) {
ExtensionElement jobCategoryElement = jobCategoryElements.get(0); if (StringUtils.isNotEmpty(jobCategoryElement.getElementText())) { Expression categoryExpression = processEngineConfiguration.getExpressionManager().createExpression(jobCategoryElement.getElementText()); Object categoryValue = categoryExpression.getValue(execution); if (categoryValue != null) { job.setCategory(categoryValue.toString()); } } } // Inherit tenant id (if applicable) if (execution.getTenantId() != null) { job.setTenantId(execution.getTenantId()); } return job; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\JobUtil.java
1
请完成以下Java代码
public void updateQtyCU(final I_C_OrderLine orderLine, final ICalloutField field) { final IHUPackingAware packingAware = new OrderLineHUPackingAware(orderLine); setQtuCUFromQtyTU(packingAware); packingAwareBL.setQtyLUFromQtyTU(packingAware); // Update lineNetAmt, because QtyEnteredCU changed : see task 06727 Services.get(IOrderLineBL.class).updateLineNetAmtFromQtyEntered(orderLine); } private void setQtuCUFromQtyTU(final IHUPackingAware packingAware) { final int qtyPacks = packingAware.getQtyTU().intValue(); packingAwareBL.setQtyCUFromQtyTU(packingAware, qtyPacks); } @CalloutMethod(columnNames = { I_C_OrderLine.COLUMNNAME_QtyLU, I_C_OrderLine.COLUMNNAME_M_LU_HU_PI_ID }) public void updateQtyTUCU(final I_C_OrderLine orderLine, final ICalloutField field) { packingAwareBL.validateLUQty(orderLine.getQtyLU());
final IHUPackingAware packingAware = new OrderLineHUPackingAware(orderLine); packingAwareBL.setQtyTUFromQtyLU(packingAware); updateQtyCU(orderLine, field); } @CalloutMethod(columnNames = { I_C_OrderLine.COLUMNNAME_C_BPartner_ID , I_C_OrderLine.COLUMNNAME_QtyEntered , I_C_OrderLine.COLUMNNAME_M_HU_PI_Item_Product_ID , I_C_OrderLine.COLUMNNAME_M_Product_ID }) public void onHURelevantChange(final I_C_OrderLine orderLine, final ICalloutField field) { final I_C_OrderLine ol = InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class); Services.get(IHUOrderBL.class).updateOrderLine(ol, field.getColumnName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\callout\C_OrderLine.java
1
请完成以下Java代码
public JsonObject toJsonObject(QueryOrderingProperty property) { JsonObject jsonObject = JsonUtil.createObject(); JsonUtil.addField(jsonObject, RELATION, property.getRelation()); QueryProperty queryProperty = property.getQueryProperty(); if (queryProperty != null) { JsonUtil.addField(jsonObject, QUERY_PROPERTY, queryProperty.getName()); JsonUtil.addField(jsonObject, QUERY_PROPERTY_FUNCTION, queryProperty.getFunction()); } Direction direction = property.getDirection(); if (direction != null) { JsonUtil.addField(jsonObject, DIRECTION, direction.getName()); } if (property.hasRelationConditions()) { JsonArray relationConditionsJson = JsonQueryFilteringPropertyConverter.ARRAY_CONVERTER .toJsonArray(property.getRelationConditions()); JsonUtil.addField(jsonObject, RELATION_CONDITIONS, relationConditionsJson); } return jsonObject; } public QueryOrderingProperty toObject(JsonObject jsonObject) { String relation = null; if (jsonObject.has(RELATION)) { relation = JsonUtil.getString(jsonObject, RELATION); } QueryOrderingProperty property = null; if (QueryOrderingProperty.RELATION_VARIABLE.equals(relation)) { property = new VariableOrderProperty(); } else { property = new QueryOrderingProperty(); } property.setRelation(relation); if (jsonObject.has(QUERY_PROPERTY)) {
String propertyName = JsonUtil.getString(jsonObject, QUERY_PROPERTY); String propertyFunction = null; if (jsonObject.has(QUERY_PROPERTY_FUNCTION)) { propertyFunction = JsonUtil.getString(jsonObject, QUERY_PROPERTY_FUNCTION); } QueryProperty queryProperty = new QueryPropertyImpl(propertyName, propertyFunction); property.setQueryProperty(queryProperty); } if (jsonObject.has(DIRECTION)) { String direction = JsonUtil.getString(jsonObject, DIRECTION); property.setDirection(Direction.findByName(direction)); } if (jsonObject.has(RELATION_CONDITIONS)) { List<QueryEntityRelationCondition> relationConditions = JsonQueryFilteringPropertyConverter.ARRAY_CONVERTER.toObject(JsonUtil.getArray(jsonObject, RELATION_CONDITIONS)); property.setRelationConditions(relationConditions); } return property; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\json\JsonQueryOrderingPropertyConverter.java
1
请完成以下Java代码
public static List<TsKvEntry> toTimeseries(Map<String, List<JsonNode>> timeseries) { if (!CollectionUtils.isEmpty(timeseries)) { List<TsKvEntry> result = new ArrayList<>(); timeseries.forEach((key, values) -> result.addAll(values.stream().map(ts -> { KvEntry entry = parseValue(key, ts.get(VALUE)); return new BasicTsKvEntry(ts.get(TS).asLong(), entry); } ).toList()) ); return result; } else { return Collections.emptyList(); } } private static KvEntry parseValue(String key, JsonNode value) { if (!value.isContainerNode()) { if (value.isBoolean()) { return new BooleanDataEntry(key, value.asBoolean()); } else if (value.isNumber()) { return parseNumericValue(key, value); } else if (value.isTextual()) { return new StringDataEntry(key, value.asText());
} else { throw new RuntimeException(CAN_T_PARSE_VALUE + value); } } else { return new JsonDataEntry(key, value.toString()); } } private static KvEntry parseNumericValue(String key, JsonNode value) { if (value.isFloatingPointNumber()) { return new DoubleDataEntry(key, value.asDouble()); } else { try { long longValue = Long.parseLong(value.toString()); return new LongDataEntry(key, longValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Big integer values are not supported!"); } } } }
repos\thingsboard-master\rest-client\src\main\java\org\thingsboard\rest\client\utils\RestJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode == null ? null : payWayCode.trim(); } public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName == null ? null : payWayName.trim(); } public Date getPaySuccessTime() { return paySuccessTime; } public void setPaySuccessTime(Date paySuccessTime) { this.paySuccessTime = paySuccessTime; } public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getIsRefund() { return isRefund; } public void setIsRefund(String isRefund) { this.isRefund = isRefund == null ? null : isRefund.trim(); }
public Short getRefundTimes() { return refundTimes; } public void setRefundTimes(Short refundTimes) { this.refundTimes = refundTimes; } public BigDecimal getSuccessRefundAmount() { return successRefundAmount; } public void setSuccessRefundAmount(BigDecimal successRefundAmount) { this.successRefundAmount = successRefundAmount; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java
2
请完成以下Java代码
public class ValidationResultsCollectorImpl implements ValidationResultCollector { protected ModelElementInstance currentElement; protected Map<ModelElementInstance, List<ValidationResult>> collectedResults = new HashMap<ModelElementInstance, List<ValidationResult>>(); protected int errorCount = 0; protected int warningCount = 0; @Override public void addError(int code, String message) { resultsForCurrentElement() .add(new ModelValidationResultImpl(currentElement, ValidationResultType.ERROR, code, message)); ++errorCount; } @Override public void addWarning(int code, String message) { resultsForCurrentElement() .add(new ModelValidationResultImpl(currentElement, ValidationResultType.WARNING, code, message)); ++warningCount; }
public void setCurrentElement(ModelElementInstance currentElement) { this.currentElement = currentElement; } public ValidationResults getResults() { return new ModelValidationResultsImpl(collectedResults, errorCount, warningCount); } protected List<ValidationResult> resultsForCurrentElement() { List<ValidationResult> resultsByElement = collectedResults.get(currentElement); if(resultsByElement == null) { resultsByElement = new ArrayList<ValidationResult>(); collectedResults.put(currentElement, resultsByElement); } return resultsByElement; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\validation\ValidationResultsCollectorImpl.java
1
请完成以下Java代码
public IHUAssignmentBuilder setVHU(final I_M_HU vhu) { this.vhu = vhu; return this; } @Override public IHUAssignmentBuilder setQty(final BigDecimal qty) { this.qty = qty; return this; } @Override public IHUAssignmentBuilder setIsTransferPackingMaterials(final boolean isTransferPackingMaterials) { this.isTransferPackingMaterials = isTransferPackingMaterials; return this; } @Override public IHUAssignmentBuilder setIsActive(final boolean isActive) { this.isActive = isActive; return this; } @Override public boolean isActive() { return isActive; } @Override public I_M_HU_Assignment getM_HU_Assignment() { return assignment; } @Override public boolean isNewAssignment() { return InterfaceWrapperHelper.isNew(assignment); } @Override public IHUAssignmentBuilder initializeAssignment(final Properties ctx, final String trxName) { final I_M_HU_Assignment assignment = InterfaceWrapperHelper.create(ctx, I_M_HU_Assignment.class, trxName); setAssignmentRecordToUpdate(assignment); return this; } @Override public IHUAssignmentBuilder setTemplateForNewRecord(final I_M_HU_Assignment assignmentRecord) { this.assignment = newInstance(I_M_HU_Assignment.class); return updateFromRecord(assignmentRecord); }
@Override public IHUAssignmentBuilder setAssignmentRecordToUpdate(@NonNull final I_M_HU_Assignment assignmentRecord) { this.assignment = assignmentRecord; return updateFromRecord(assignmentRecord); } private IHUAssignmentBuilder updateFromRecord(final I_M_HU_Assignment assignmentRecord) { setTopLevelHU(assignmentRecord.getM_HU()); setM_LU_HU(assignmentRecord.getM_LU_HU()); setM_TU_HU(assignmentRecord.getM_TU_HU()); setVHU(assignmentRecord.getVHU()); setQty(assignmentRecord.getQty()); setIsTransferPackingMaterials(assignmentRecord.isTransferPackingMaterials()); setIsActive(assignmentRecord.isActive()); return this; } @Override public I_M_HU_Assignment build() { Check.assumeNotNull(model, "model not null"); Check.assumeNotNull(topLevelHU, "topLevelHU not null"); Check.assumeNotNull(assignment, "assignment not null"); TableRecordCacheLocal.setReferencedValue(assignment, model); assignment.setM_HU(topLevelHU); assignment.setM_LU_HU(luHU); assignment.setM_TU_HU(tuHU); assignment.setVHU(vhu); assignment.setQty(qty); assignment.setIsTransferPackingMaterials(isTransferPackingMaterials); assignment.setIsActive(isActive); InterfaceWrapperHelper.save(assignment); return assignment; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBuilder.java
1
请完成以下Java代码
public class InstanceWebClient { public static final String ATTRIBUTE_INSTANCE = "instance"; private final WebClient webClient; protected InstanceWebClient(WebClient webClient) { this.webClient = webClient; } public WebClient instance(Mono<Instance> instance) { return this.webClient.mutate().filters((filters) -> filters.add(0, setInstance(instance))).build(); } public WebClient instance(Instance instance) { return this.instance(Mono.justOrEmpty(instance)); } public static InstanceWebClient.Builder builder() { return new InstanceWebClient.Builder(); } public static InstanceWebClient.Builder builder(WebClient.Builder webClient) { return new InstanceWebClient.Builder(webClient); } private static ExchangeFilterFunction setInstance(Mono<Instance> instance) { return (request, next) -> instance .map((i) -> ClientRequest.from(request).attribute(ATTRIBUTE_INSTANCE, i).build()) .switchIfEmpty(Mono.error(() -> new ResolveInstanceException("Could not resolve Instance"))) .flatMap(next::exchange); } private static ExchangeFilterFunction toExchangeFilterFunction(InstanceExchangeFilterFunction filter) { return (request, next) -> request.attribute(ATTRIBUTE_INSTANCE) .filter(Instance.class::isInstance) .map(Instance.class::cast) .map((instance) -> filter.filter(instance, request, next)) .orElseGet(() -> next.exchange(request)); } public static class Builder { private List<InstanceExchangeFilterFunction> filters = new ArrayList<>(); private WebClient.Builder webClientBuilder;
public Builder() { this(WebClient.builder()); } public Builder(WebClient.Builder webClientBuilder) { this.webClientBuilder = webClientBuilder; } protected Builder(Builder other) { this.filters = new ArrayList<>(other.filters); this.webClientBuilder = other.webClientBuilder.clone(); } public Builder filter(InstanceExchangeFilterFunction filter) { this.filters.add(filter); return this; } public Builder filters(Consumer<List<InstanceExchangeFilterFunction>> filtersConsumer) { filtersConsumer.accept(this.filters); return this; } public Builder webClient(WebClient.Builder builder) { this.webClientBuilder = builder; return this; } public Builder clone() { return new Builder(this); } public InstanceWebClient build() { this.filters.stream() .map(InstanceWebClient::toExchangeFilterFunction) .forEach(this.webClientBuilder::filter); return new InstanceWebClient(this.webClientBuilder.build()); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\InstanceWebClient.java
1
请完成以下Java代码
public int conversion(LocalDate birthDate){ return Period.between(birthDate, LocalDate.now()).getYears(); } // constructors public UserDto() { super(); } public UserDto(long id, String username, int age) { super(); this.id = id; this.username = username; this.age = age; } // getters and setters public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) {
this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]"; } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\jmapper\UserDto.java
1
请完成以下Java代码
public Map<String, VariableInstance> execute(CommandContext commandContext) { // Verify existence of execution if (executionId == null) { throw new FlowableIllegalArgumentException("executionId is null"); } ExecutionEntity execution = commandContext.getExecutionEntityManager().findExecutionById(executionId); if (execution == null) { throw new FlowableObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class); } Map<String, VariableInstance> variables = null; if (variableNames == null || variableNames.isEmpty()) { // Fetch all if (isLocal) { variables = execution.getVariableInstancesLocal(); } else {
variables = execution.getVariableInstances(); } } else { // Fetch specific collection of variables if (isLocal) { variables = execution.getVariableInstancesLocal(variableNames, false); } else { variables = execution.getVariableInstances(variableNames, false); } } return variables; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\GetExecutionVariableInstancesCmd.java
1
请在Spring Boot框架中完成以下Java代码
private Mono<AuthorizationDecision> toDecision(ClientResponse response) { if (!response.statusCode() .is2xxSuccessful()) { return Mono.just(new AuthorizationDecision(false)); } return response.bodyToMono(ObjectNode.class) .map(node -> { boolean authorized = node.path("result") .path("authorized") .asBoolean(false); return new AuthorizationDecision(authorized); }); } private Publisher<Map<String, Object>> toAuthorizationPayload(Mono<Authentication> auth, AuthorizationContext context) { return auth.defaultIfEmpty( new AnonymousAuthenticationToken("**ANONYMOUS**", new Object(), Collections.singletonList(new SimpleGrantedAuthority("ANONYMOUS")))) .map(a -> { Map<String, String> headers = context.getExchange() .getRequest() .getHeaders() .toSingleValueMap(); Map<String, Object> attributes = ImmutableMap.<String, Object> builder()
.put("principal", a.getName()) .put("authorities", a.getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList())) .put("uri", context.getExchange() .getRequest() .getURI() .getPath()) .put("headers", headers) .build(); return ImmutableMap.<String, Object> builder() .put("input", attributes) .build(); }); } }
repos\tutorials-master\spring-security-modules\spring-security-opa\src\main\java\com\baeldung\security\opa\config\SecurityConfiguration.java
2
请完成以下Java代码
public void setSocketTimeout(Duration socketTimeout) { setSocketTimeout(Math.toIntExact(socketTimeout.toMillis())); } public FlowableHttpClient getHttpClient() { return httpClient; } public void setHttpClient(FlowableHttpClient httpClient) { this.httpClient = httpClient; this.closeRunnable = null; } public FlowableHttpClient determineHttpClient() { if (httpClient != null) { return httpClient; } else if (isApacheHttpComponentsPresent) { // Backwards compatibility, if apache HTTP Components is present then it has priority this.httpClient = new ApacheHttpComponentsFlowableHttpClient(this); return this.httpClient; } else if (isSpringWebClientPresent && isReactorHttpClientPresent) { this.httpClient = new SpringWebClientFlowableHttpClient(this); return httpClient; } else if (isApacheHttpComponents5Present) { ApacheHttpComponents5FlowableHttpClient httpClient = new ApacheHttpComponents5FlowableHttpClient(this); this.httpClient = httpClient; this.closeRunnable = httpClient::close; return this.httpClient; } else { throw new FlowableException("Failed to determine FlowableHttpClient");
} } public boolean isDefaultParallelInSameTransaction() { return defaultParallelInSameTransaction; } public void setDefaultParallelInSameTransaction(boolean defaultParallelInSameTransaction) { this.defaultParallelInSameTransaction = defaultParallelInSameTransaction; } public void close() { if (closeRunnable != null) { closeRunnable.run(); } } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\HttpClientConfig.java
1
请完成以下Java代码
public class Personne { private String nom; private String surnom; private int age; public Personne(String nom, String surnom, int age) { this.nom = nom; this.surnom = surnom; this.age = age; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getSurnom() { return surnom; }
public void setSurnom(String surnom) { this.surnom = surnom; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Personne [nom=" + nom + ", surnom=" + surnom + ", age=" + age + "]"; } }
repos\tutorials-master\orika\src\main\java\com\baeldung\orika\Personne.java
1
请在Spring Boot框架中完成以下Java代码
public class KairosProperties extends StepRegistryProperties { /** * URI of the KairosDB server. */ private String uri = "http://localhost:8080/api/v1/datapoints"; /** * Login user of the KairosDB server. */ private @Nullable String userName; /** * Login password of the KairosDB server. */ private @Nullable String password; public String getUri() { return this.uri; }
public void setUri(String uri) { this.uri = uri; } public @Nullable String getUserName() { return this.userName; } public void setUserName(@Nullable String userName) { this.userName = userName; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\kairos\KairosProperties.java
2
请完成以下Java代码
public DmnDeploymentQueryImpl decisionKey(String key) { if (key == null) { throw new FlowableIllegalArgumentException("key is null"); } this.decisionKey = key; return this; } @Override public DmnDeploymentQueryImpl decisionKeyLike(String keyLike) { if (keyLike == null) { throw new FlowableIllegalArgumentException("keyLike is null"); } this.decisionKeyLike = keyLike; return this; } // sorting //////////////////////////////////////////////////////// @Override public DmnDeploymentQuery orderByDeploymentId() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_ID); } @Override public DmnDeploymentQuery orderByDeploymentTime() { return orderBy(DeploymentQueryProperty.DEPLOY_TIME); } @Override public DmnDeploymentQuery orderByDeploymentName() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_NAME); } @Override public DmnDeploymentQuery orderByTenantId() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_TENANT_ID); } // results //////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getDeploymentEntityManager(commandContext).findDeploymentCountByQueryCriteria(this); } @Override public List<DmnDeployment> executeList(CommandContext commandContext) { return CommandContextUtil.getDeploymentEntityManager(commandContext).findDeploymentsByQueryCriteria(this); }
// getters //////////////////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getDecisionKey() { return decisionKey; } public String getDecisionKeyLike() { return decisionKeyLike; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnDeploymentQueryImpl.java
1
请完成以下Java代码
private void onParameterChanged_ActionTUToNewLUs(final String parameterName) { @SuppressWarnings("ConstantConditions") // at this point i don't think the HU can be null. final BigDecimal realTUQty = huTransformService.getMaximumQtyTU(getSingleSelectedRow().getM_HU()).toBigDecimal(); if (PARAM_Action.equals(parameterName)) { final I_M_HU_PI_Item defaultHUPIItem = newParametersFiller().getDefaultM_LU_PI_ItemOrNull(); p_M_HU_PI_Item = defaultHUPIItem; if (defaultHUPIItem != null) { p_QtyTU = realTUQty.min(defaultHUPIItem.getQty()); } } else if (PARAM_M_HU_PI_Item_ID.equals(parameterName) && p_M_HU_PI_Item != null) { p_QtyTU = realTUQty.min(p_M_HU_PI_Item.getQty()); } } private void onParameterChanged_ActionCUToNewTUs() { final Optional<I_M_HU_PI_Item_Product> packingItemOptional = newParametersFiller().getDefaultM_HU_PI_Item_Product(); if (packingItemOptional.isPresent()) { final BigDecimal realCUQty = getSingleSelectedRow().getQtyCU(); p_M_HU_PI_Item_Product = packingItemOptional.get(); p_QtyCUsPerTU = realCUQty.min(packingItemOptional.get().getQty()); } } private void moveToWarehouse(final WebuiHUTransformCommandResult result) { if (moveToWarehouseId != null && showWarehouse) { final ImmutableList<I_M_HU> createdHUs = result.getHuIdsCreated()
.stream() .map(handlingUnitsDAO::getById) .collect(ImmutableList.toImmutableList()); huMovementBL.moveHUsToWarehouse(createdHUs, moveToWarehouseId); } } private void setShowWarehouseFlag() { this.showWarehouse = newParametersFiller().getShowWarehouseFlag(); if (!this.showWarehouse) { this.moveToWarehouseId = null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Transform.java
1
请完成以下Java代码
public class C_Invoice_Candidate_TabCallout extends TabCalloutAdapter implements IStatefulTabCallout { private FacetExecutor<I_C_Invoice_Candidate> gridTabFacetExecutor; /** * Action: Approve for invoicing (selected invoice candidates) */ private IC_ApproveForInvoicing_Action action_ApproveForInvoicing = null; @Override public void onInit(final ICalloutRecord calloutRecord) { final GridTab gridTab = GridTab.fromCalloutRecordOrNull(calloutRecord); if(gridTab == null) { return; } final ISideActionsGroupsListModel sideActionsGroupsModel = gridTab.getSideActionsGroupsModel(); // // Add action: Approve For Invoicing (08602) { action_ApproveForInvoicing = new IC_ApproveForInvoicing_Action(gridTab); sideActionsGroupsModel .getGroupById(GridTab.SIDEACTIONS_Actions_GroupId) .addAction(action_ApproveForInvoicing); } // // Setup facet filtering engine (08602) { gridTabFacetExecutor = new FacetExecutor<>(I_C_Invoice_Candidate.class); // Current facets will be displayed in GridTab's right-side panel final IFacetsPool<I_C_Invoice_Candidate> facetsPool = new SideActionFacetsPool<>(sideActionsGroupsModel); gridTabFacetExecutor.setFacetsPool(facetsPool); // The datasource which will be filtered by our facets is actually THIS grid tab final IFacetFilterable<I_C_Invoice_Candidate> facetFilterable = new GridTabFacetFilterable<>(I_C_Invoice_Candidate.class, gridTab); gridTabFacetExecutor.setFacetFilterable(facetFilterable); // We will use service registered collectors to collect the facets from invoice candidates final IFacetCollector<I_C_Invoice_Candidate> facetCollectors = Services.get(IInvoiceCandidateFacetCollectorFactory.class).createFacetCollectors(); gridTabFacetExecutor.addFacetCollector(facetCollectors); } }
@Override public void onAfterQuery(final ICalloutRecord calloutRecord) { updateFacets(calloutRecord); } @Override public void onRefreshAll(final ICalloutRecord calloutRecord) { // NOTE: we are not updating the facets on refresh all because following case would fail: // Case: user is pressing the "Refresh" toolbar button to refresh THE content of the grid, // but user is not expecting to have all it's facets reset. // updateFacets(gridTab); } /** * Retrieve invoice candidates facets from current grid tab rows and add them to window side panel * * @param calloutRecord * @param http://dewiki908/mediawiki/index.php/08602_Rechnungsdispo_UI_%28106621797084%29 */ private void updateFacets(final ICalloutRecord calloutRecord) { // // If user asked to approve for invoicing some ICs, the grid will be asked to refresh all, // but in this case we don't want to reset current facets and recollect them if (action_ApproveForInvoicing.isRunning()) { return; } // // Collect the facets from current grid tab rows and fully update the facets pool. gridTabFacetExecutor.collectFacetsAndResetPool(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\callout\C_Invoice_Candidate_TabCallout.java
1
请完成以下Java代码
private static Object normalizeSingleArgumentBeforeFormat(@Nullable final Object arg, final String adLanguage) { if (arg == null) { return null; } else if (arg instanceof ITranslatableString) { return ((ITranslatableString)arg).translate(adLanguage); } else if (arg instanceof Amount) { return TranslatableStrings.amount((Amount)arg).translate(adLanguage); } else if (arg instanceof ReferenceListAwareEnum) { return normalizeSingleArgumentBeforeFormat_ReferenceListAwareEnum((ReferenceListAwareEnum)arg, adLanguage); } else if (arg instanceof Iterable) { @SuppressWarnings("unchecked") final Iterable<Object> iterable = (Iterable<Object>)arg; return normalizeSingleArgumentBeforeFormat_Iterable(iterable, adLanguage); } else { return arg; } } private static Object normalizeSingleArgumentBeforeFormat_ReferenceListAwareEnum( @NonNull final ReferenceListAwareEnum referenceListAwareEnum, final String adLanguage) { final int adReferenceId = ReferenceListAwareEnums.getAD_Reference_ID(referenceListAwareEnum); if (adReferenceId > 0) { final ADReferenceService adReferenceService = ADReferenceService.get(); final ADRefListItem adRefListItem = adReferenceService.retrieveListItemOrNull(adReferenceId, referenceListAwareEnum.getCode()); if (adRefListItem != null) { return adRefListItem.getName().translate(adLanguage); } } // Fallback return referenceListAwareEnum.toString(); }
private static String normalizeSingleArgumentBeforeFormat_Iterable( @NonNull final Iterable<Object> iterable, final String adLanguage) { final StringBuilder result = new StringBuilder(); for (final Object item : iterable) { String itemNormStr; try { final Object itemNormObj = normalizeSingleArgumentBeforeFormat(item, adLanguage); itemNormStr = itemNormObj != null ? itemNormObj.toString() : "-"; } catch (Exception ex) { s_log.warn("Failed normalizing argument `{}`. Using toString().", item, ex); itemNormStr = item.toString(); } if (!(result.length() == 0)) { result.append(", "); } result.append(itemNormStr); } return result.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\MessageFormatter.java
1
请完成以下Java代码
public void addResolver(HandlerMethodArgumentResolver resolver) { this.argumentResolvers.add(resolver); } /** * Return a read-only list with the contained resolvers, or an empty list. */ public List<HandlerMethodArgumentResolver> getResolvers() { return Collections.unmodifiableList(this.argumentResolvers); } /** * Whether the given {@linkplain MethodParameter method parameter} is * supported by any registered {@link HandlerMethodArgumentResolver}. */ @Override public boolean supportsParameter(MethodParameter parameter) { return (getArgumentResolver(parameter) != null); } /** * Iterate over registered * {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers} * and invoke the one that supports it. * @throws IllegalArgumentException if no suitable argument resolver is found */ @Override public @Nullable Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) throws Exception { HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); if (resolver == null) { throw new IllegalArgumentException("Unsupported parameter [%s].".formatted(parameter)); }
return resolver.resolveArgument(parameter, environment); } /** * Find a registered {@link HandlerMethodArgumentResolver} that supports * the given method parameter. * @param parameter the method parameter */ public @Nullable HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) { return this.argumentResolverCache.computeIfAbsent(parameter, (p) -> { for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) { if (resolver.supportsParameter(parameter)) { return resolver; } } return null; }); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\HandlerMethodArgumentResolverComposite.java
1
请完成以下Java代码
public int getCM_Media_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Media_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Media_Server getCM_Media_Server() throws RuntimeException { return (I_CM_Media_Server)MTable.get(getCtx(), I_CM_Media_Server.Table_Name) .getPO(getCM_Media_Server_ID(), get_TrxName()); } /** Set Media Server. @param CM_Media_Server_ID Media Server list to which content should get transfered */ public void setCM_Media_Server_ID (int CM_Media_Server_ID) { if (CM_Media_Server_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Media_Server_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Media_Server_ID, Integer.valueOf(CM_Media_Server_ID)); } /** Get Media Server. @return Media Server list to which content should get transfered */ public int getCM_Media_Server_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Media_Server_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Deployed. @param IsDeployed
Entity is deployed */ public void setIsDeployed (boolean IsDeployed) { set_Value (COLUMNNAME_IsDeployed, Boolean.valueOf(IsDeployed)); } /** Get Deployed. @return Entity is deployed */ public boolean isDeployed () { Object oo = get_Value(COLUMNNAME_IsDeployed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Synchronized. @param LastSynchronized Date when last synchronized */ public void setLastSynchronized (Timestamp LastSynchronized) { set_Value (COLUMNNAME_LastSynchronized, LastSynchronized); } /** Get Last Synchronized. @return Date when last synchronized */ public Timestamp getLastSynchronized () { return (Timestamp)get_Value(COLUMNNAME_LastSynchronized); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_MediaDeploy.java
1
请完成以下Java代码
static Access extractPermission(final I_AD_User_Record_Access record) { return Access.ofCode(record.getAccess()); } private static ImmutableSet<RecordAccessId> extractIds(final Collection<I_AD_User_Record_Access> accessRecords) { return accessRecords.stream() .map(RecordAccessService::extractId) .collect(ImmutableSet.toImmutableSet()); } private static RecordAccessId extractId(final I_AD_User_Record_Access record) { return RecordAccessId.ofRepoId(record.getAD_User_Record_Access_ID()); } @Nullable public String buildUserGroupRecordAccessSqlWhereClause( final String tableName, @NonNull final AdTableId adTableId, @NonNull final String keyColumnNameFQ, @NonNull final UserId userId, @NonNull final Set<UserGroupId> userGroupIds, @NonNull final RoleId roleId) { if (!isApplyUserGroupRecordAccess(roleId, tableName)) { return null; } final StringBuilder sql = new StringBuilder(); sql.append(" EXISTS (SELECT 1 FROM " + I_AD_User_Record_Access.Table_Name + " z " + " WHERE " + " z.AD_Table_ID = ").append(adTableId.getRepoId()).append(" AND z.Record_ID=").append(keyColumnNameFQ).append(" AND z.IsActive='Y'"); // // User or User Group sql.append(" AND (AD_User_ID=").append(userId.getRepoId()); if (!userGroupIds.isEmpty()) { sql.append(" OR ").append(DB.buildSqlList("z.AD_UserGroup_ID", userGroupIds)); } sql.append(")"); // sql.append(" )"); // EXISTS // return sql.toString(); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean isApplyUserGroupRecordAccess( @NonNull final RoleId roleId, @NonNull final String tableName) {
return configs .getByRoleId(roleId) .isTableHandled(tableName); } public boolean hasRecordPermission( @NonNull final UserId userId, @NonNull final RoleId roleId, @NonNull final TableRecordReference recordRef, @NonNull final Access permission) { if (!isApplyUserGroupRecordAccess(roleId, recordRef.getTableName())) { return true; } final RecordAccessQuery query = RecordAccessQuery.builder() .recordRef(recordRef) .permission(permission) .principals(getPrincipals(userId)) .build(); return recordAccessRepository.query(query) .addOnlyActiveRecordsFilter() .create() .anyMatch(); } private Set<Principal> getPrincipals(@NonNull final UserId userId) { final ImmutableSet.Builder<Principal> principals = ImmutableSet.builder(); principals.add(Principal.userId(userId)); for (final UserGroupId userGroupId : userGroupsRepo.getAssignedGroupIdsByUserId(userId)) { principals.add(Principal.userGroupId(userGroupId)); } return principals.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccessService.java
1
请完成以下Java代码
public Object setVariableLocal(String variableName, Object value) { return null; } @Override public void setVariablesLocal(Map<String, ? extends Object> variables) { } @Override public boolean isEventScope() { return isEventScope; } @Override public void setEventScope(boolean isEventScope) { this.isEventScope = isEventScope; } @Override public StartingExecution getStartingExecution() { return startingExecution; } @Override public void disposeStartingExecution() { startingExecution = null; } public String updateProcessBusinessKey(String bzKey) { return getProcessInstance().updateProcessBusinessKey(bzKey); } @Override public String getTenantId() { return null; // Not implemented } // NOT IN V5 @Override public boolean isMultiInstanceRoot() { return false; } @Override public void setMultiInstanceRoot(boolean isMultiInstanceRoot) { } @Override public String getPropagatedStageInstanceId() { return null; } // No support for transient variables in v5 @Override public void setTransientVariablesLocal(Map<String, Object> transientVariables) { throw new UnsupportedOperationException(); } @Override public void setTransientVariableLocal(String variableName, Object variableValue) { throw new UnsupportedOperationException(); } @Override public void setTransientVariables(Map<String, Object> transientVariables) { throw new UnsupportedOperationException(); } @Override public void setTransientVariable(String variableName, Object variableValue) { throw new UnsupportedOperationException();
} @Override public Object getTransientVariableLocal(String variableName) { throw new UnsupportedOperationException(); } @Override public Map<String, Object> getTransientVariablesLocal() { throw new UnsupportedOperationException(); } @Override public Object getTransientVariable(String variableName) { throw new UnsupportedOperationException(); } @Override public Map<String, Object> getTransientVariables() { throw new UnsupportedOperationException(); } @Override public void removeTransientVariableLocal(String variableName) { throw new UnsupportedOperationException(); } @Override public void removeTransientVariablesLocal() { throw new UnsupportedOperationException(); } @Override public void removeTransientVariable(String variableName) { throw new UnsupportedOperationException(); } @Override public void removeTransientVariables() { throw new UnsupportedOperationException(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\ExecutionImpl.java
1
请完成以下Java代码
public void setGroupProductBOMId(@NonNull final GroupId groupId, @NonNull final ProductBOMId bomId) { final I_C_Order_CompensationGroup groupRecord = retrieveGroupRecord(groupId); groupRecord.setPP_Product_BOM_ID(bomId.getRepoId()); saveRecord(groupRecord); } @Nullable public GroupTemplateId getGroupTemplateId(@NonNull final GroupId groupId) { return queryBL .createQueryBuilder(I_C_Order_CompensationGroup.class) .addEqualsFilter(I_C_Order_CompensationGroup.COLUMNNAME_C_Order_CompensationGroup_ID, groupId.getOrderCompensationGroupId()) .andCollect(I_C_Order_CompensationGroup.COLUMNNAME_C_CompensationGroup_Schema_ID, I_C_CompensationGroup_Schema.class) .create() .firstIdOnly(GroupTemplateId::ofRepoIdOrNull); } public I_C_OrderLine createRegularLineFromTemplate( @NonNull final GroupTemplateRegularLine from, @NonNull final I_C_Order targetOrder,
final @NonNull RetrieveOrCreateGroupRequest request) { final I_C_OrderLine orderLine = orderLineBL.createOrderLine(targetOrder); final ProductId productId = from.getProductId(); orderLine.setM_Product_ID(productId.getRepoId()); orderLine.setM_AttributeSetInstance_ID(AttributeSetInstanceId.NONE.getRepoId()); orderLine.setC_UOM_ID(from.getQty().getUomId().getRepoId()); orderLine.setQtyEntered(request.getQtyMultiplier().multiply(from.getQty().toBigDecimal())); orderLine.setC_CompensationGroup_Schema_TemplateLine_ID(from.getId().getRepoId()); orderLine.setC_Flatrate_Conditions_ID(ConditionsId.toRepoId(request.getNewContractConditionsId())); orderLine.setIsAllowSeparateInvoicing(from.isAllowSeparateInvoicing()); orderLine.setIsHideWhenPrinting(from.isHideWhenPrinting()); orderLineBL.save(orderLine); return orderLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderGroupRepository.java
1
请完成以下Java代码
public boolean doCatch(Throwable e) throws Throwable { exception = e; throw e; } @Override public void doFinally() { if (ExecutionResult.Ignored == executionResult) { // do nothing return; } setExecutionStatus(); InterfaceWrapperHelper.save(step); } /** * After step execution, sets ErrorMsg, StatusCode, Apply */ private void setExecutionStatus() { // Success if (exception == null) { Check.assumeNotNull(executionResult, "executionResult not null"); step.setErrorMsg(null); if (executionResult == ExecutionResult.Executed) { if (action == Action.Apply) { step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Applied); } else if (action == Action.Rollback) { step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Unapplied);
} else { throw new AdempiereException("Unknown action: " + action); } } else if (executionResult == ExecutionResult.Skipped) { step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Unapplied); } else { throw new AdempiereException("Unknown execution result: " + executionResult); } } // Error / Warning else { logger.error("Action " + action + " of " + step + " failed.", exception); step.setErrorMsg(exception.getLocalizedMessage()); if (action == Action.Apply) { step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Failed); step.setApply(X_AD_MigrationStep.APPLY_Apply); } } if (X_AD_MigrationStep.STATUSCODE_Applied.equals(step.getStatusCode())) { step.setApply(X_AD_MigrationStep.APPLY_Rollback); } else if (X_AD_MigrationStep.STATUSCODE_Unapplied.equals(step.getStatusCode())) { step.setApply(X_AD_MigrationStep.APPLY_Apply); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationStepExecutorRunnable.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public String getProductUnit() { return productUnit; } public void setProductUnit(String productUnit) { this.productUnit = productUnit; } public Integer getNavStatus() { return navStatus; } public void setNavStatus(Integer navStatus) { this.navStatus = navStatus; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) {
this.keywords = keywords; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @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(", parentId=").append(parentId); sb.append(", name=").append(name); sb.append(", level=").append(level); sb.append(", productCount=").append(productCount); sb.append(", productUnit=").append(productUnit); sb.append(", navStatus=").append(navStatus); sb.append(", showStatus=").append(showStatus); sb.append(", sort=").append(sort); sb.append(", icon=").append(icon); sb.append(", keywords=").append(keywords); sb.append(", description=").append(description); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductCategory.java
1
请完成以下Java代码
public void setExportStatus (final java.lang.String ExportStatus) { set_Value (COLUMNNAME_ExportStatus, ExportStatus); } @Override public java.lang.String getExportStatus() { return get_ValueAsString(COLUMNNAME_ExportStatus); } @Override public void setM_ReceiptSchedule_ExportAudit_ID (final int M_ReceiptSchedule_ExportAudit_ID) { if (M_ReceiptSchedule_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID, M_ReceiptSchedule_ExportAudit_ID); } @Override public int getM_ReceiptSchedule_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID); } @Override public de.metas.inoutcandidate.model.I_M_ReceiptSchedule getM_ReceiptSchedule() { return get_ValueAsPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class); } @Override public void setM_ReceiptSchedule(final de.metas.inoutcandidate.model.I_M_ReceiptSchedule M_ReceiptSchedule) { set_ValueFromPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class, M_ReceiptSchedule); } @Override public void setM_ReceiptSchedule_ID (final int M_ReceiptSchedule_ID) { if (M_ReceiptSchedule_ID < 1) set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null); else
set_Value (COLUMNNAME_M_ReceiptSchedule_ID, M_ReceiptSchedule_ID); } @Override public int getM_ReceiptSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule_ExportAudit.java
1
请完成以下Java代码
private void updateDatevAcctExport() { final String tableName = getTableName(); if (I_DatevAcctExport.Table_Name.equals(tableName)) { final int recordId = getRecord_ID(); final I_DatevAcctExport datevAcctExport = InterfaceWrapperHelper.create(getCtx(), recordId, I_DatevAcctExport.class, getTrxName()); final AdProcessId adProcessId = getProcessInfo().getAdProcessId(); final I_AD_Process processRecord = adProcessDAO.getById(adProcessId); if (processRecord.isUpdateExportDate()) { datevAcctExport.setExportDate(SystemTime.asTimestamp()); } datevAcctExport.setExportBy_ID(getAD_User_ID()); InterfaceWrapperHelper.saveRecord(datevAcctExport); } } private String getSql() { return getProcessInfo().getSQLStatement().orElseThrow(() -> new FillMandatoryException("SQLStatement")); } private Evaluatee getEvalContext() { final ArrayList<Evaluatee> contexts = new ArrayList<>(); // // 1: Add process parameters contexts.add(Evaluatees.ofRangeAwareParams(getParameterAsIParams())); // // 2: underlying record final String recordTableName = getTableName(); final int recordId = getRecord_ID(); if (recordTableName != null && recordId > 0)
{ final TableRecordReference recordRef = TableRecordReference.of(recordTableName, recordId); final Evaluatee evalCtx = Evaluatees.ofTableRecordReference(recordRef); if (evalCtx != null) { contexts.add(evalCtx); } } // // 3: global context contexts.add(Evaluatees.ofCtx(getCtx())); return Evaluatees.compose(contexts); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\process\ExportToSpreadsheetProcess.java
1
请完成以下Java代码
public Collection<EntryCriterion> getEntryCriterions() { return entryCriterionCollection.get(this); } public Collection<ExitCriterion> getExitCriterions() { return exitCriterionCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DiscretionaryItem.class, CMMN_ELEMENT_DISCRETIONARY_ITEM) .namespaceUri(CMMN11_NS) .extendsType(TableItem.class) .instanceProvider(new ModelTypeInstanceProvider<DiscretionaryItem>() { public DiscretionaryItem newInstance(ModelTypeInstanceContext instanceContext) { return new DiscretionaryItemImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF)
.idAttributeReference(PlanItemDefinition.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\DiscretionaryItemImpl.java
1
请完成以下Java代码
private int reusableTopicAttempts() { if (this.isSameIntervalReuse && this.backOffValues.size() > 1) { // Assuming that duplicates are always at the end of the list. return amountOfDuplicates(this.backOffValues.get(this.backOffValues.size() - 1)) - 1; } return 0; } private boolean hasDuplicates(Long thisBackOffValue) { return amountOfDuplicates(thisBackOffValue) > 1; } private int amountOfDuplicates(Long thisBackOffValue) { return Long.valueOf(this.backOffValues .stream() .filter(thisBackOffValue::equals) .count()) .intValue(); } private DestinationTopic.Properties createProperties(long delayMs, String suffix) { return new DestinationTopic.Properties(delayMs, suffix, getDestinationTopicType(delayMs), this.maxAttempts, this.numPartitions, this.dltStrategy, this.kafkaOperations, this.shouldRetryOn, this.timeout); } private String joinWithRetrySuffix(long parameter) { return String.join("-", this.destinationTopicSuffixes.getRetrySuffix(), String.valueOf(parameter)); } public static class DestinationTopicSuffixes { private final String retryTopicSuffix;
private final String dltSuffix; public DestinationTopicSuffixes(@Nullable String retryTopicSuffix, @Nullable String dltSuffix) { this.retryTopicSuffix = StringUtils.hasText(retryTopicSuffix) ? retryTopicSuffix : RetryTopicConstants.DEFAULT_RETRY_SUFFIX; this.dltSuffix = StringUtils.hasText(dltSuffix) ? dltSuffix : RetryTopicConstants.DEFAULT_DLT_SUFFIX; } public String getRetrySuffix() { return this.retryTopicSuffix; } public String getDltSuffix() { return this.dltSuffix; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopicPropertiesFactory.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } public I_M_FreightCost getM_FreightCost() throws RuntimeException { return (I_M_FreightCost)MTable.get(getCtx(), I_M_FreightCost.Table_Name) .getPO(getM_FreightCost_ID(), get_TrxName()); } /** Set Frachtkostenpauschale. @param M_FreightCost_ID Frachtkostenpauschale */ public void setM_FreightCost_ID (int M_FreightCost_ID) { if (M_FreightCost_ID < 1) set_ValueNoCheck (COLUMNNAME_M_FreightCost_ID, null); else set_ValueNoCheck (COLUMNNAME_M_FreightCost_ID, Integer.valueOf(M_FreightCost_ID)); } /** Get Frachtkostenpauschale. @return Frachtkostenpauschale */ public int getM_FreightCost_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCost_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lieferweg-Versandkosten. @param M_FreightCostShipper_ID Lieferweg-Versandkosten */ public void setM_FreightCostShipper_ID (int M_FreightCostShipper_ID) { if (M_FreightCostShipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, Integer.valueOf(M_FreightCostShipper_ID)); } /** Get Lieferweg-Versandkosten. @return Lieferweg-Versandkosten */ public int getM_FreightCostShipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCostShipper_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Shipper getM_Shipper() throws RuntimeException { return (I_M_Shipper)MTable.get(getCtx(), I_M_Shipper.Table_Name) .getPO(getM_Shipper_ID(), get_TrxName()); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); }
/** Get Lieferweg. @return Methode oder Art der Warenlieferung */ public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gueltig ab. @param ValidFrom Gueltig ab inklusiv (erster Tag) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gueltig ab. @return Gueltig ab inklusiv (erster Tag) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCostShipper.java
1
请完成以下Java代码
public static IHostIdentifier of(@NonNull final InetAddress inetAddress) { final String hostAddress = inetAddress.getHostAddress(); final String hostName = inetAddress.getHostName(); return new HostIdentifier(hostName, hostAddress); } @Immutable private static final class HostIdentifier implements IHostIdentifier { private final String hostName; private final String hostAddress; private transient String _toString; private transient Integer _hashcode; private HostIdentifier(final String hostName, final String hostAddress) { this.hostAddress = hostAddress; this.hostName = hostName; } @Override public String toString() { if (_toString == null) { _toString = (hostName != null ? hostName : "") + "/" + hostAddress; } return _toString; } @Override public int hashCode() { if (_hashcode == null) { _hashcode = Objects.hash(hostName, hostAddress); } return _hashcode; }
@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof HostIdentifier) { final HostIdentifier other = (HostIdentifier)obj; return Objects.equals(hostName, other.hostName) && Objects.equals(hostAddress, other.hostAddress); } else { return false; } } @Override public String getIP() { return hostAddress; } @Override public String getHostName() { return hostName; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\net\NetUtils.java
1
请完成以下Java代码
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); }
/** Set Issue Recommendation. @param R_IssueRecommendation_ID Recommendations how to fix an Issue */ public void setR_IssueRecommendation_ID (int R_IssueRecommendation_ID) { if (R_IssueRecommendation_ID < 1) set_ValueNoCheck (COLUMNNAME_R_IssueRecommendation_ID, null); else set_ValueNoCheck (COLUMNNAME_R_IssueRecommendation_ID, Integer.valueOf(R_IssueRecommendation_ID)); } /** Get Issue Recommendation. @return Recommendations how to fix an Issue */ public int getR_IssueRecommendation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueRecommendation_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueRecommendation.java
1
请完成以下Java代码
public void setVariableNameIgnoreCase(boolean variableNameIgnoreCase) { this.variableNameIgnoreCase = variableNameIgnoreCase; } public boolean isVariableValueIgnoreCase() { return variableValueIgnoreCase; } public void setVariableValueIgnoreCase(boolean variableValueIgnoreCase) { this.variableValueIgnoreCase = variableValueIgnoreCase; } @Override public boolean equals(Object o) { if (this == o)
return true; if (o == null || getClass() != o.getClass()) return false; QueryVariableValue that = (QueryVariableValue) o; return local == that.local && variableNameIgnoreCase == that.variableNameIgnoreCase && variableValueIgnoreCase == that.variableValueIgnoreCase && name.equals(that.name) && value.equals(that.value) && operator == that.operator && Objects.equals(valueCondition, that.valueCondition); } @Override public int hashCode() { return Objects.hash(name, value, operator, local, valueCondition, variableNameIgnoreCase, variableValueIgnoreCase); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryVariableValue.java
1
请完成以下Java代码
public ExitCriterion getExitCriterion() { return exitCriterionRefAttribute.getReferenceTargetElement(this); } public void setExitCriterion(ExitCriterion exitCriterion) { exitCriterionRefAttribute.setReferenceTargetElement(this, exitCriterion); } public PlanItem getSource() { return sourceRefAttribute.getReferenceTargetElement(this); } public void setSource(PlanItem source) { sourceRefAttribute.setReferenceTargetElement(this, source); } public PlanItemTransition getStandardEvent() { PlanItemTransitionStandardEvent child = standardEventChild.getChild(this); return child.getValue(); } public void setStandardEvent(PlanItemTransition standardEvent) { PlanItemTransitionStandardEvent child = standardEventChild.getChild(this); child.setValue(standardEvent); } 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
请完成以下Java代码
public boolean supports(Class<?> clazz) { return true; } @Override public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { if (authentication == null) { return ACCESS_DENIED; } int result = ACCESS_ABSTAIN; Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication); for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { result = ACCESS_DENIED; // Attempt to find a matching granted authority
for (GrantedAuthority authority : authorities) { if (attribute.getAttribute().equals(authority.getAuthority())) { return ACCESS_GRANTED; } } } } return result; } Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) { return authentication.getAuthorities(); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\RoleVoter.java
1
请在Spring Boot框架中完成以下Java代码
class DynatracePropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<DynatraceProperties> implements DynatraceConfig { DynatracePropertiesConfigAdapter(DynatraceProperties properties) { super(properties); } @Override public String prefix() { return "management.dynatrace.metrics.export"; } @Override public String apiToken() { return obtain(DynatraceProperties::getApiToken, DynatraceConfig.super::apiToken); } @Override public String deviceId() { return obtain(v1(V1::getDeviceId), DynatraceConfig.super::deviceId); } @Override public String technologyType() { return obtain(v1(V1::getTechnologyType), DynatraceConfig.super::technologyType); } @Override public String uri() { return obtain(DynatraceProperties::getUri, DynatraceConfig.super::uri); } @Override public @Nullable String group() { return get(v1(V1::getGroup), DynatraceConfig.super::group); } @Override public DynatraceApiVersion apiVersion() { return obtain((properties) -> (properties.getV1().getDeviceId() != null) ? DynatraceApiVersion.V1 : DynatraceApiVersion.V2, DynatraceConfig.super::apiVersion); } @Override public String metricKeyPrefix() {
return obtain(v2(V2::getMetricKeyPrefix), DynatraceConfig.super::metricKeyPrefix); } @Override public Map<String, String> defaultDimensions() { return obtain(v2(V2::getDefaultDimensions), DynatraceConfig.super::defaultDimensions); } @Override public boolean enrichWithDynatraceMetadata() { return obtain(v2(V2::isEnrichWithDynatraceMetadata), DynatraceConfig.super::enrichWithDynatraceMetadata); } @Override public boolean useDynatraceSummaryInstruments() { return obtain(v2(V2::isUseDynatraceSummaryInstruments), DynatraceConfig.super::useDynatraceSummaryInstruments); } @Override public boolean exportMeterMetadata() { return obtain(v2(V2::isExportMeterMetadata), DynatraceConfig.super::exportMeterMetadata); } private <V> Getter<DynatraceProperties, V> v1(Getter<V1, V> getter) { return (properties) -> getter.get(properties.getV1()); } private <V> Getter<DynatraceProperties, V> v2(Getter<V2, V> getter) { return (properties) -> getter.get(properties.getV2()); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatracePropertiesConfigAdapter.java
2
请完成以下Java代码
public static void streamFeed() { StatusListener listener = new StatusListener(){ @Override public void onException(Exception e) { e.printStackTrace(); } @Override public void onDeletionNotice(StatusDeletionNotice arg) { System.out.println("Got a status deletion notice id:" + arg.getStatusId()); } @Override public void onScrubGeo(long userId, long upToStatusId) { System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { System.out.println("Got stall warning:" + warning); }
@Override public void onStatus(Status status) { System.out.println(status.getUser().getName() + " : " + status.getText()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); twitterStream.sample(); } }
repos\tutorials-master\saas-modules\twitter4j\src\main\java\com\baeldung\Application.java
1
请完成以下Java代码
static class TopicCreation { private final boolean shouldCreateTopics; private final int numPartitions; private final short replicationFactor; TopicCreation(@Nullable Boolean shouldCreate, @Nullable Integer numPartitions, @Nullable Short replicationFactor) { this.shouldCreateTopics = shouldCreate == null || shouldCreate; this.numPartitions = numPartitions == null ? 1 : numPartitions; this.replicationFactor = replicationFactor == null ? -1 : replicationFactor; } TopicCreation() { this.shouldCreateTopics = true; this.numPartitions = 1; this.replicationFactor = -1; } TopicCreation(boolean shouldCreateTopics) {
this.shouldCreateTopics = shouldCreateTopics; this.numPartitions = 1; this.replicationFactor = -1; } public int getNumPartitions() { return this.numPartitions; } public short getReplicationFactor() { return this.replicationFactor; } public boolean shouldCreateTopics() { return this.shouldCreateTopics; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public class WebConfig implements WebMvcConfigurer { /** * Spring Boot allows configuring Content Negotiation using properties */ @Override public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { configurer.favorParameter(true) .parameterName("mediaType") .ignoreAcceptHeader(false) .useRegisteredExtensionsOnly(false) .defaultContentType(MediaType.APPLICATION_JSON) .mediaType("xml", MediaType.APPLICATION_XML) .mediaType("json", MediaType.APPLICATION_JSON); } @Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() { return factory -> factory.setRegisterDefaultServlet(true); } @Bean public Greeting greeting() { Greeting greeting = new Greeting(); greeting.setMessage("Hello World !!"); return greeting; } @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); bean.setOrder(2); return bean;
} @Bean public BeanNameViewResolver beanNameViewResolver(){ BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver(); beanNameViewResolver.setOrder(1); return beanNameViewResolver; } @Bean public View sample() { return new JstlView("/WEB-INF/view/sample.jsp"); } @Bean public View sample2() { return new JstlView("/WEB-INF/view2/sample2.jsp"); } @Bean public View sample3(){ return new JstlView("/WEB-INF/view3/sample3.jsp"); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-4\src\main\java\com\baeldung\config\WebConfig.java
2
请完成以下Java代码
public void setIMP_ProcessorLog_ID (int IMP_ProcessorLog_ID) { if (IMP_ProcessorLog_ID < 1) set_ValueNoCheck (COLUMNNAME_IMP_ProcessorLog_ID, null); else set_ValueNoCheck (COLUMNNAME_IMP_ProcessorLog_ID, Integer.valueOf(IMP_ProcessorLog_ID)); } /** Get Import Processor Log. @return Import Processor Log */ public int getIMP_ProcessorLog_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_ProcessorLog_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Error. @param IsError An Error occurred in the execution */ public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Error. @return An Error occurred in the execution */ public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reference. @param Reference Reference for this record */ public void setReference (String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Reference. @return Reference for this record */ public String getReference () { return (String)get_Value(COLUMNNAME_Reference); }
/** Set Summary. @param Summary Textual summary of this request */ public void setSummary (String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ public String getSummary () { return (String)get_Value(COLUMNNAME_Summary); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_ProcessorLog.java
1
请完成以下Java代码
void close() throws IOException { synchronized (this.lock) { if (this.referenceCount == 0) { return; } this.referenceCount--; if (this.referenceCount == 0) { debug.log("Closing '%s'", this.path); this.buffer = null; this.bufferPosition = -1; this.bufferSize = 0; this.fileChannel.close(); tracker.closedFileChannel(this.path); this.fileChannel = null; if (this.randomAccessFile != null) { this.randomAccessFile.close(); tracker.closedFileChannel(this.path); this.randomAccessFile = null; } } debug.log("Reference count for '%s' decremented to %s", this.path, this.referenceCount); } } <E extends Exception> void ensureOpen(Supplier<E> exceptionSupplier) throws E { synchronized (this.lock) { if (this.referenceCount == 0) { throw exceptionSupplier.get(); } } } @Override public String toString() {
return this.path.toString(); } } /** * Internal tracker used to check open and closing of files in tests. */ interface Tracker { Tracker NONE = new Tracker() { @Override public void openedFileChannel(Path path) { } @Override public void closedFileChannel(Path path) { } }; void openedFileChannel(Path path); void closedFileChannel(Path path); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\FileDataBlock.java
1
请完成以下Java代码
private Object formatCell(final Object value, final DATEVExportFormatColumn columnFormat) { if (value == null) { return null; } if (columnFormat.getDateFormatter() != null) { return formatDateCell(value, columnFormat.getDateFormatter()); } else if (columnFormat.getNumberFormatter() != null) { return formatNumberCell(value, columnFormat.getNumberFormatter()); } else { return value; } } private static String formatDateCell(final Object value, final DateTimeFormatter dateFormatter) { if (value == null) { return null; } else if (value instanceof java.util.Date) { final java.util.Date date = (java.util.Date)value; return dateFormatter.format(TimeUtil.asLocalDate(date)); }
else if (value instanceof TemporalAccessor) { TemporalAccessor temporal = (TemporalAccessor)value; return dateFormatter.format(temporal); } else { throw new AdempiereException("Cannot convert/format value to Date: " + value + " (" + value.getClass() + ")"); } } private static String formatNumberCell(final Object value, final ThreadLocalDecimalFormatter numberFormatter) { if (value == null) { return null; } return numberFormatter.format(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\DATEVCsvExporter.java
1
请完成以下Java代码
public void setSeqNo(final Integer seqNo) { this.seqNo = seqNo; this.seqNoSet = true; } public void setTaxCategory(final TaxCategory taxCategory) { this.taxCategory = taxCategory; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setUomCode(final String uomCode) { this.uomCode = uomCode; this.uomCodeSet = true; } @NonNull public String getOrgCode() { return orgCode; } @NonNull
public String getProductIdentifier() { return productIdentifier; } @NonNull public TaxCategory getTaxCategory() { return taxCategory; } @NonNull public BigDecimal getPriceStd() { return priceStd; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-pricing\src\main\java\de\metas\common\pricing\v2\productprice\JsonRequestProductPrice.java
1
请完成以下Java代码
public int available() throws IOException { return (this.available >= 0) ? this.available : super.available(); } @Override public int read(byte[] b, int off, int len) throws IOException { int result = super.read(b, off, len); if (result != -1) { this.available -= result; } return result; } @Override protected void fill() throws IOException {
try { super.fill(); } catch (EOFException ex) { if (this.extraBytesWritten) { throw ex; } this.len = 1; this.buf[0] = 0x0; this.extraBytesWritten = true; this.inf.setInput(this.buf, 0, this.len); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\ZipInflaterInputStream.java
1
请完成以下Java代码
private final void updateParentSplitPaneDividerLocation() { final JComponent comp = getComponent(); if (!comp.isVisible()) { return; // nothing to update } // Find parent split pane if any JSplitPane parentSplitPane = null; for (Component c = comp.getParent(); c != null; c = c.getParent()) { if (c instanceof JSplitPane) { parentSplitPane = (JSplitPane)c; break;
} } // Update it's divider location. // NOTE: if we would not do this, user would have to manually drag it when the first component is added. if (parentSplitPane != null) { if (parentSplitPane.getDividerLocation() <= 0) { parentSplitPane.setDividerLocation(Ini.getDividerLocation()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\FavoritesGroupContainer.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge.
@param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchPO.java
1
请完成以下Java代码
public class NERTrainer extends PerceptronTrainer { /** * 支持任意自定义NER类型,例如:<br> * tagSet.nerLabels.clear();<br> * tagSet.nerLabels.add("nr");<br> * tagSet.nerLabels.add("ns");<br> * tagSet.nerLabels.add("nt");<br> */ public NERTagSet tagSet; public NERTrainer(NERTagSet tagSet) { this.tagSet = tagSet; } public NERTrainer() { tagSet = new NERTagSet(); tagSet.nerLabels.add("nr"); tagSet.nerLabels.add("ns"); tagSet.nerLabels.add("nt"); } /** * 重载此方法以支持任意自定义NER类型,例如:<br> * NERTagSet tagSet = new NERTagSet();<br> * tagSet.nerLabels.add("nr");<br> * tagSet.nerLabels.add("ns");<br>
* tagSet.nerLabels.add("nt");<br> * return tagSet;<br> * @return */ @Override protected TagSet createTagSet() { return tagSet; } @Override protected Instance createInstance(Sentence sentence, FeatureMap featureMap) { return new NERInstance(sentence, featureMap); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\NERTrainer.java
1
请完成以下Java代码
public boolean cancel(boolean mayInterruptIfRunning) { throw new UnsupportedOperationException(); } @Override public boolean isCancelled() { return canceled; } @Override public boolean isDone() { return done; } @Override public T get() throws InterruptedException, ExecutionException { latch.await(); return get0(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { latch.await(timeout, unit); return get0(); } private T get0() throws ExecutionException {
if (!done) { throw new IllegalStateException("Value not available"); } // // We got a cancellation if (canceled) { final CancellationException cancelException = new CancellationException(exception.getLocalizedMessage()); cancelException.initCause(exception); throw cancelException; } // // We got an error if (exception != null) { throw new ExecutionException(exception); } return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\FutureValue.java
1
请在Spring Boot框架中完成以下Java代码
void register(ObservationConfig config, List<ObservationHandler<?>> handlers) { MultiValueMap<ObservationHandlerGroup, ObservationHandler<?>> grouped = new LinkedMultiValueMap<>(); List<ObservationHandler<?>> unclaimed = new ArrayList<>(); for (ObservationHandler<?> handler : handlers) { ObservationHandlerGroup group = findGroup(handler); if (group == null) { unclaimed.add(handler); } else { grouped.add(group, handler); } } for (ObservationHandlerGroup group : this.groups) { List<ObservationHandler<?>> members = grouped.get(group); if (!CollectionUtils.isEmpty(members)) { group.registerMembers(config, members); } }
if (!CollectionUtils.isEmpty(unclaimed)) { for (ObservationHandler<?> handler : unclaimed) { config.observationHandler(handler); } } } private @Nullable ObservationHandlerGroup findGroup(ObservationHandler<?> handler) { for (ObservationHandlerGroup group : this.groups) { if (group.isMember(handler)) { return group; } } return null; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationHandlerGroups.java
2
请完成以下Java代码
public class LuceneFileSearch { private Directory indexDirectory; private StandardAnalyzer analyzer; public LuceneFileSearch(Directory fsDirectory, StandardAnalyzer analyzer) { super(); this.indexDirectory = fsDirectory; this.analyzer = analyzer; } public void addFileToIndex(String filepath) throws IOException, URISyntaxException { Path path = Paths.get(getClass().getClassLoader().getResource(filepath).toURI()); File file = path.toFile(); IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); IndexWriter indexWriter = new IndexWriter(indexDirectory, indexWriterConfig); Document document = new Document(); FileReader fileReader = new FileReader(file); document.add(new TextField("contents", fileReader)); document.add(new StringField("path", file.getPath(), Field.Store.YES)); document.add(new StringField("filename", file.getName(), Field.Store.YES)); indexWriter.addDocument(document); indexWriter.close(); } public List<Document> searchFiles(String inField, String queryString) { try { Query query = new QueryParser(inField, analyzer).parse(queryString); IndexReader indexReader = DirectoryReader.open(indexDirectory); IndexSearcher searcher = new IndexSearcher(indexReader);
TopDocs topDocs = searcher.search(query, 10); List<Document> documents = new ArrayList<>(); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { documents.add(searcher.doc(scoreDoc.doc)); } return documents; } catch (IOException | ParseException e) { e.printStackTrace(); } return null; } }
repos\tutorials-master\lucene\src\main\java\com\baeldung\lucene\LuceneFileSearch.java
1
请完成以下Java代码
public RefundConfig getRefundConfigById(@NonNull final RefundConfigId refundConfigId) { for (RefundConfig refundConfig : refundConfigs) { if (refundConfig.getId().equals(refundConfigId)) { return refundConfig; } } Check.fail("This contract has no config with id={}; this={}", refundConfigId, this); return null; } public RefundMode extractRefundMode() { return RefundConfigs.extractRefundMode(refundConfigs); } public Optional<RefundConfig> getRefundConfigToUseProfitCalculation() { return getRefundConfigs() .stream() .filter(RefundConfig::isUseInProfitCalculation) .findFirst(); } /** * With this instance's {@code StartDate} as basis, the method returns the first date that is * after or at the given {@code currentDate} and that is aligned with this instance's invoice schedule. */ public NextInvoiceDate computeNextInvoiceDate(@NonNull final LocalDate currentDate) { final InvoiceSchedule invoiceSchedule = extractSingleElement(refundConfigs, RefundConfig::getInvoiceSchedule);
LocalDate date = invoiceSchedule.calculateNextDateToInvoice(startDate); while (date.isBefore(currentDate)) { final LocalDate nextDate = invoiceSchedule.calculateNextDateToInvoice(date); Check.assume(nextDate.isAfter(date), // make sure not to get stuck in an endless loop "For the given date={}, invoiceSchedule.calculateNextDateToInvoice needs to return a nextDate that is later; nextDate={}", date, nextDate); date = nextDate; } return new NextInvoiceDate(invoiceSchedule, date); } @Value public static class NextInvoiceDate { InvoiceSchedule invoiceSchedule; LocalDate dateToInvoice; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundContract.java
1
请完成以下Java代码
default void contextPrepared(ConfigurableApplicationContext context) { } /** * Called once the application context has been loaded but before it has been * refreshed. * @param context the application context */ default void contextLoaded(ConfigurableApplicationContext context) { } /** * The context has been refreshed and the application has started but * {@link CommandLineRunner CommandLineRunners} and {@link ApplicationRunner * ApplicationRunners} have not been called. * @param context the application context. * @param timeTaken the time taken to start the application or {@code null} if unknown * @since 2.6.0 */ default void started(ConfigurableApplicationContext context, @Nullable Duration timeTaken) { } /** * Called immediately before the run method finishes, when the application context has * been refreshed and all {@link CommandLineRunner CommandLineRunners} and
* {@link ApplicationRunner ApplicationRunners} have been called. * @param context the application context. * @param timeTaken the time taken for the application to be ready or {@code null} if * unknown * @since 2.6.0 */ default void ready(ConfigurableApplicationContext context, @Nullable Duration timeTaken) { } /** * Called when a failure occurs when running the application. * @param context the application context or {@code null} if a failure occurred before * the context was created * @param exception the failure * @since 2.0.0 */ default void failed(@Nullable ConfigurableApplicationContext context, Throwable exception) { } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationRunListener.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getLineNo() { return lineNo; } public BigDecimal getQtyCUsPerTU() { return qtyCUsPerTU; } public BigDecimal getQtyTUs() { return qtyTUs; } public BigDecimal getQtyInUOM() { return qtyInUOM; } public String getUOM_x12de355() { return UOM_x12de355; } public String getPriceUOM_x12de355() { return priceUOM_x12de355; } public BigDecimal getPrice() { return price; } public String getCurrencyISOCode() { return currencyISOCode; } public String getPOReference() { return POReference; } public Date getDateCandidate() { return dateCandidate; } public Date getDatePromised() { return datePromised; } public int getM_Product_ID() { return M_Product_ID; } public String getProductDescription() { return productDescription; }
public String getProductAttributes() { return productAttributes; } public int getM_ProductPrice_ID() { return M_ProductPrice_ID; } public int getM_ProductPrice_Attribute_ID() { return M_ProductPrice_Attribute_ID; } public int getM_HU_PI_Item_Product_ID() { return M_HU_PI_Item_Product_ID; } public int getC_BPartner_ID() { return C_BPartner_ID; } public int getC_BPartner_Location_ID() { return C_BPartner_Location_ID; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\Excel_OLCand_Row.java
2