instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void enqueueMessage(final WebsocketTopicName destination, final Message<?> message) { final WebsocketEvent event = WebsocketEvent.builder() .destination(destination) .payload(message) .converted(true) .build(); if (doAutoflush) { debouncer.add(event); } else { enqueue(event); } } private void enqueue(@NonNull final WebsocketEvent event)
{ events.add(event); logger.debug("[name={}] Enqueued event={}", name, event); } public void sendEventsAndClear() { logger.debug("Sending all queued events"); final List<WebsocketEvent> eventsToSend = new ArrayList<>(events); events.clear(); debouncer.addAll(eventsToSend); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\sender\WebsocketSender.java
1
请完成以下Java代码
public void setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPO_PaymentTerm_ID (final int PO_PaymentTerm_ID) { if (PO_PaymentTerm_ID < 1) set_Value (COLUMNNAME_PO_PaymentTerm_ID, null); else set_Value (COLUMNNAME_PO_PaymentTerm_ID, PO_PaymentTerm_ID); } @Override public int getPO_PaymentTerm_ID() { return get_ValueAsInt(COLUMNNAME_PO_PaymentTerm_ID); } @Override public void setPO_PricingSystem_ID (final int PO_PricingSystem_ID) { if (PO_PricingSystem_ID < 1) set_Value (COLUMNNAME_PO_PricingSystem_ID, null); else set_Value (COLUMNNAME_PO_PricingSystem_ID, PO_PricingSystem_ID); } @Override public int getPO_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_PO_PricingSystem_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() {
return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setReferrer (final @Nullable java.lang.String Referrer) { set_Value (COLUMNNAME_Referrer, Referrer); } @Override public java.lang.String getReferrer() { return get_ValueAsString(COLUMNNAME_Referrer); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput.java
1
请完成以下Java代码
public int getHR_Payroll_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Payroll_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Employee. @param IsEmployee Indicates if this Business Partner is an employee */ public void setIsEmployee (boolean IsEmployee) { set_Value (COLUMNNAME_IsEmployee, Boolean.valueOf(IsEmployee)); } /** Get Employee. @return Indicates if this Business Partner is an employee */ public boolean isEmployee () { Object oo = get_Value(COLUMNNAME_IsEmployee); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName ()
{ return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_List.java
1
请完成以下Java代码
public class DatabaseDto { protected String vendor; protected String version; public DatabaseDto(String vendor, String version) { this.vendor = vendor; this.version = version; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor;
} public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public static DatabaseDto fromEngineDto(Database other) { return new DatabaseDto( other.getVendor(), other.getVersion()); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\DatabaseDto.java
1
请完成以下Java代码
public void handleInvoiceChangedEvent(@NonNull final InvoiceChangedEvent event) { // NOTE: only sales invoices are supported atm if (!event.getSoTrx().isSales()) { return; } final BPartnerId bpartnerId = event.getBpartnerId(); final Set<ProductId> productIds = event.getProductIds(); if (event.isReversal()) { statsRepo.recomputeStatistics(RecomputeStatisticsRequest.builder() .bpartnerId(bpartnerId) .productIds(productIds) .recomputeInvoiceStatistics(true) .build()); } else { final ImmutableMap<ProductId, BPartnerProductStats> statsByProductId = statsRepo.getByPartnerAndProducts(bpartnerId, productIds); for (final ProductId productId : productIds) { BPartnerProductStats stats = statsByProductId.get(productId);
if (stats == null) { stats = BPartnerProductStats.newInstance(bpartnerId, productId); } final BPartnerProductStats.LastInvoiceInfo lastSalesInvoice = extractLastSalesInvoiceInfo(event, productId); stats.updateLastSalesInvoiceInfo(lastSalesInvoice); statsRepo.save(stats); } } } private static BPartnerProductStats.LastInvoiceInfo extractLastSalesInvoiceInfo(final InvoiceChangedEvent event, final ProductId productId) { return BPartnerProductStats.LastInvoiceInfo.builder() .invoiceId(event.getInvoiceId()) .invoiceDate(event.getInvoiceDate()) .price(event.getProductPrice(productId)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\BPartnerProductStatsEventHandler.java
1
请完成以下Java代码
public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public de.metas.handlingunits.model.I_M_HU getM_LU_HU() { return get_ValueAsPO(COLUMNNAME_M_LU_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setM_LU_HU(final de.metas.handlingunits.model.I_M_HU M_LU_HU) { set_ValueFromPO(COLUMNNAME_M_LU_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_LU_HU); } @Override public void setM_LU_HU_ID (final int M_LU_HU_ID) { if (M_LU_HU_ID < 1) set_Value (COLUMNNAME_M_LU_HU_ID, null); else set_Value (COLUMNNAME_M_LU_HU_ID, M_LU_HU_ID); } @Override public int getM_LU_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_LU_HU_ID); } @Override public de.metas.handlingunits.model.I_M_HU getM_TU_HU() { return get_ValueAsPO(COLUMNNAME_M_TU_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setM_TU_HU(final de.metas.handlingunits.model.I_M_HU M_TU_HU) { set_ValueFromPO(COLUMNNAME_M_TU_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_TU_HU); } @Override public void setM_TU_HU_ID (final int M_TU_HU_ID) { if (M_TU_HU_ID < 1) set_Value (COLUMNNAME_M_TU_HU_ID, null); else set_Value (COLUMNNAME_M_TU_HU_ID, M_TU_HU_ID); } @Override public int getM_TU_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_TU_HU_ID); } @Override public void setProducts (final @Nullable java.lang.String Products) { throw new IllegalArgumentException ("Products is virtual column"); } @Override public java.lang.String getProducts() { return get_ValueAsString(COLUMNNAME_Products); } @Override public void setQty (final @Nullable BigDecimal Qty)
{ set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public de.metas.handlingunits.model.I_M_HU getVHU() { return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU) { set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Assignment.java
1
请完成以下Java代码
public void exportS3Storage(HttpServletResponse response, S3StorageQueryCriteria criteria) throws IOException { s3StorageService.download(s3StorageService.queryAll(criteria), response); } @GetMapping @ApiOperation("查询文件") @PreAuthorize("@el.check('storage:list')") public ResponseEntity<PageResult<S3Storage>> queryS3Storage(S3StorageQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(s3StorageService.queryAll(criteria, pageable),HttpStatus.OK); } @PostMapping @ApiOperation("上传文件") public ResponseEntity<Object> uploadS3Storage(@RequestParam MultipartFile file){ S3Storage storage = s3StorageService.upload(file); Map<String,Object> map = new HashMap<>(3); map.put("id",storage.getId()); map.put("errno",0); map.put("data",new String[]{amzS3Config.getDomain() + "/" + storage.getFilePath()}); return new ResponseEntity<>(map,HttpStatus.OK); } @Log("下载文件") @ApiOperation("下载文件") @GetMapping(value = "/download/{id}") public ResponseEntity<Object> downloadS3Storage(@PathVariable Long id){ Map<String,Object> map = new HashMap<>(1); S3Storage storage = s3StorageService.getById(id);
if (storage == null) { map.put("message", "文件不存在或已被删除"); return new ResponseEntity<>(map, HttpStatus.NOT_FOUND); } // 仅适合公开文件访问,私有文件可以使用服务中的 privateDownload 方法 String url = amzS3Config.getDomain() + "/" + storage.getFilePath(); map.put("url", url); return new ResponseEntity<>(map,HttpStatus.OK); } @Log("删除多个文件") @DeleteMapping @ApiOperation("删除多个文件") @PreAuthorize("@el.check('storage:del')") public ResponseEntity<Object> deleteAllS3Storage(@RequestBody List<Long> ids) { s3StorageService.deleteAll(ids); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\rest\S3StorageController.java
1
请完成以下Java代码
public abstract class AbstractBehaviorFactory { protected ExpressionManager expressionManager; private ThrowMessageDelegateFactory throwMessageDelegateFactory = new ThrowMessageDelegateFactory() {}; private MessagePayloadMappingProviderFactory messagePayloadMappingProviderFactory = new BpmnMessagePayloadMappingProviderFactory(); private MessageExecutionContextFactory messageExecutionContextFactory = new DefaultMessageExecutionContextFactory(); public List<FieldDeclaration> createFieldDeclarations(List<FieldExtension> fieldList) { List<FieldDeclaration> fieldDeclarations = new ArrayList<FieldDeclaration>(); for (FieldExtension fieldExtension : fieldList) { FieldDeclaration fieldDeclaration = null; if (StringUtils.isNotEmpty(fieldExtension.getExpression())) { fieldDeclaration = new FieldDeclaration( fieldExtension.getFieldName(), Expression.class.getName(), expressionManager.createExpression(fieldExtension.getExpression()) ); } else { fieldDeclaration = new FieldDeclaration( fieldExtension.getFieldName(), Expression.class.getName(), new FixedValue(fieldExtension.getStringValue()) ); } fieldDeclarations.add(fieldDeclaration); } return fieldDeclarations; } public ExpressionManager getExpressionManager() {
return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public ThrowMessageDelegateFactory getThrowMessageDelegateFactory() { return throwMessageDelegateFactory; } public void setThrowMessageDelegateFactory(ThrowMessageDelegateFactory throwMessageDelegateFactory) { this.throwMessageDelegateFactory = throwMessageDelegateFactory; } public MessagePayloadMappingProviderFactory getMessagePayloadMappingProviderFactory() { return messagePayloadMappingProviderFactory; } public void setMessagePayloadMappingProviderFactory( MessagePayloadMappingProviderFactory messagePayloadMappingProviderFactory ) { this.messagePayloadMappingProviderFactory = messagePayloadMappingProviderFactory; } public MessageExecutionContextFactory getMessageExecutionContextFactory() { return messageExecutionContextFactory; } public void setMessageExecutionContextFactory(MessageExecutionContextFactory messageExecutionContextFactory) { this.messageExecutionContextFactory = messageExecutionContextFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\AbstractBehaviorFactory.java
1
请完成以下Java代码
public int getRetryOnFailure() {return retryOnFailure;} @Override public ILockCommand setRecordByModel(final Object model) { _recordsToLock.setRecordByModel(model); return this; } @Override public ILockCommand setRecordByTableRecordId(final int tableId, final int recordId) { _recordsToLock.setRecordByTableRecordId(tableId, recordId); return this; } @Override public ILockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId pinstanceId) { _recordsToLock.setRecordsBySelection(modelClass, pinstanceId); return this; } @Override public <T> ILockCommand setRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters) { _recordsToLock.setRecordsByFilter(clazz, filters); return this; } @Override public <T> ILockCommand addRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters) { _recordsToLock.addRecordsByFilter(clazz, filters); return this; } @Override public List<LockRecordsByFilter> getSelectionToLock_Filters() { return _recordsToLock.getSelection_Filters(); } @Override
public final AdTableId getSelectionToLock_AD_Table_ID() { return _recordsToLock.getSelection_AD_Table_ID(); } @Override public final PInstanceId getSelectionToLock_AD_PInstance_ID() { return _recordsToLock.getSelection_PInstanceId(); } @Override public final Iterator<TableRecordReference> getRecordsToLockIterator() { return _recordsToLock.getRecordsIterator(); } @Override public LockCommand addRecordByModel(final Object model) { _recordsToLock.addRecordByModel(model); return this; } @Override public LockCommand addRecordsByModel(final Collection<?> models) { _recordsToLock.addRecordByModels(models); return this; } @Override public ILockCommand addRecord(@NonNull final TableRecordReference record) { _recordsToLock.addRecords(ImmutableSet.of(record)); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockCommand.java
1
请完成以下Java代码
public void setLine (BigDecimal Line) { set_Value (COLUMNNAME_Line, Line); } /** Get Line No. @return Unique line for this document */ public BigDecimal getLine () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Line); if (bd == null) return Env.ZERO; return bd; } /** 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 PA_DashboardContent_ID. @param PA_DashboardContent_ID PA_DashboardContent_ID */ public void setPA_DashboardContent_ID (int PA_DashboardContent_ID) { if (PA_DashboardContent_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, Integer.valueOf(PA_DashboardContent_ID)); } /** Get PA_DashboardContent_ID. @return PA_DashboardContent_ID */ public int getPA_DashboardContent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_DashboardContent_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Goal getPA_Goal() throws RuntimeException { return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name) .getPO(getPA_Goal_ID(), get_TrxName()); } /** Set Goal. @param PA_Goal_ID Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID) { if (PA_Goal_ID < 1)
set_Value (COLUMNNAME_PA_Goal_ID, null); else set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID)); } /** Get Goal. @return Performance Goal */ public int getPA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ZUL File Path. @param ZulFilePath Absolute path to zul file */ public void setZulFilePath (String ZulFilePath) { set_Value (COLUMNNAME_ZulFilePath, ZulFilePath); } /** Get ZUL File Path. @return Absolute path to zul file */ public String getZulFilePath () { return (String)get_Value(COLUMNNAME_ZulFilePath); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_DashboardContent.java
1
请完成以下Java代码
public String format(Map<String, ? extends OptionDescriptor> options) { Comparator<OptionDescriptor> comparator = Comparator .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); Set<OptionDescriptor> sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { if (!descriptor.representsNonOptions()) { this.help.add(new OptionHelpAdapter(descriptor)); } } return ""; } Collection<OptionHelp> getOptionHelp() { return Collections.unmodifiableList(this.help); } } private static class OptionHelpAdapter implements OptionHelp { private final Set<String> options; private final String description; OptionHelpAdapter(OptionDescriptor descriptor) { this.options = new LinkedHashSet<>(); for (String option : descriptor.options()) { String prefix = (option.length() != 1) ? "--" : "-"; this.options.add(prefix + option); }
if (this.options.contains("--cp")) { this.options.remove("--cp"); this.options.add("-cp"); } this.description = descriptor.description(); } @Override public Set<String> getOptions() { return this.options; } @Override public String getUsageHelp() { return this.description; } } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\options\OptionHandler.java
1
请完成以下Java代码
public void setIsSelfService (boolean IsSelfService) { set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService)); } /** Get Self-Service. @return This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_R_Group getR_Group() throws RuntimeException { return (I_R_Group)MTable.get(getCtx(), I_R_Group.Table_Name) .getPO(getR_Group_ID(), get_TrxName()); } /** Set Group. @param R_Group_ID Request Group */ public void setR_Group_ID (int R_Group_ID) { if (R_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_R_Group_ID, Integer.valueOf(R_Group_ID)); } /** Get Group. @return Request Group */ public int getR_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Group_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_GroupUpdates.java
1
请完成以下Java代码
public void remove(String id) { cache.remove(id); } public Object get(String id) { HalResourceCacheEntry cacheEntry = cache.get(id); if (cacheEntry != null) { if (expired(cacheEntry)) { remove(cacheEntry.getId()); return null; } else { return cacheEntry.getResource(); } } else { return null; } } public void destroy() { cache.clear(); } protected void ensureCapacityLimit() { if (size() > getCapacity()) { List<HalResourceCacheEntry> resources = new ArrayList<HalResourceCacheEntry>(cache.values()); NavigableSet<HalResourceCacheEntry> remainingResources = new TreeSet<HalResourceCacheEntry>(COMPARATOR); // remove expired resources for (HalResourceCacheEntry resource : resources) { if (expired(resource)) { remove(resource.getId()); } else { remainingResources.add(resource); } if (size() <= getCapacity()) {
// abort if capacity is reached return; } } // if still exceed capacity remove oldest while (remainingResources.size() > capacity) { HalResourceCacheEntry resourceToRemove = remainingResources.pollFirst(); if (resourceToRemove != null) { remove(resourceToRemove.getId()); } else { break; } } } } protected boolean expired(HalResourceCacheEntry entry) { return entry.getCreateTime() + secondsToLive * 1000 < ClockUtil.getCurrentTime().getTime(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\DefaultHalResourceCache.java
1
请完成以下Java代码
public class EngineTemperatureSensor implements Callable<Void> { private static final Logger log = LoggerFactory.getLogger(EngineTemperatureSensor.class); public static final String TOPIC = "engine/temperature"; private IMqttClient client; private Random rnd = new Random(); public EngineTemperatureSensor(IMqttClient client) { this.client = client; } @Override public Void call() throws Exception { if ( !client.isConnected()) { log.info("[I31] Client not connected."); return null; }
MqttMessage msg = readEngineTemp(); msg.setQos(0); msg.setRetained(true); client.publish(TOPIC,msg); return null; } /** * This method simulates reading the engine temperature * @return */ private MqttMessage readEngineTemp() { double temp = 80 + rnd.nextDouble() * 20.0; byte[] payload = String.format("T:%04.2f",temp).getBytes(); MqttMessage msg = new MqttMessage(payload); return msg; } }
repos\tutorials-master\libraries-server\src\main\java\com\baeldung\mqtt\EngineTemperatureSensor.java
1
请完成以下Java代码
public PartyIdentificationSEPA4 getOrgnlCdtrSchmeId() { return orgnlCdtrSchmeId; } /** * Sets the value of the orgnlCdtrSchmeId property. * * @param value * allowed object is * {@link PartyIdentificationSEPA4 } * */ public void setOrgnlCdtrSchmeId(PartyIdentificationSEPA4 value) { this.orgnlCdtrSchmeId = value; } /** * Gets the value of the orgnlDbtrAcct property. * * @return * possible object is * {@link CashAccountSEPA2 } * */ public CashAccountSEPA2 getOrgnlDbtrAcct() { return orgnlDbtrAcct; } /** * Sets the value of the orgnlDbtrAcct property. * * @param value * allowed object is * {@link CashAccountSEPA2 } * */
public void setOrgnlDbtrAcct(CashAccountSEPA2 value) { this.orgnlDbtrAcct = value; } /** * Gets the value of the orgnlDbtrAgt property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentificationSEPA2 } * */ public BranchAndFinancialInstitutionIdentificationSEPA2 getOrgnlDbtrAgt() { return orgnlDbtrAgt; } /** * Sets the value of the orgnlDbtrAgt property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentificationSEPA2 } * */ public void setOrgnlDbtrAgt(BranchAndFinancialInstitutionIdentificationSEPA2 value) { this.orgnlDbtrAgt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\AmendmentInformationDetailsSDD.java
1
请完成以下Java代码
public static Collector<PickingJobCandidateProduct, ?, PickingJobCandidateProducts> collect() { return GuavaCollectors.collectUsingListAccumulator(PickingJobCandidateProducts::ofList); } public Set<ProductId> getProductIds() {return byProductId.keySet();} @Override @NonNull public Iterator<PickingJobCandidateProduct> iterator() {return byProductId.values().iterator();} public OptionalBoolean hasQtyAvailableToPick() { final QtyAvailableStatus qtyAvailableStatus = getQtyAvailableStatus().orElse(null); return qtyAvailableStatus == null ? OptionalBoolean.UNKNOWN : OptionalBoolean.ofBoolean(qtyAvailableStatus.isPartialOrFullyAvailable()); } public Optional<QtyAvailableStatus> getQtyAvailableStatus() { Optional<QtyAvailableStatus> qtyAvailableStatus = this._qtyAvailableStatus; //noinspection OptionalAssignedToNull if (qtyAvailableStatus == null) { qtyAvailableStatus = this._qtyAvailableStatus = computeQtyAvailableStatus(); } return qtyAvailableStatus; } private Optional<QtyAvailableStatus> computeQtyAvailableStatus() { return QtyAvailableStatus.computeOfLines(byProductId.values(), product -> product.getQtyAvailableStatus().orElse(null)); } public PickingJobCandidateProducts updatingEachProduct(@NonNull UnaryOperator<PickingJobCandidateProduct> updater) { if (byProductId.isEmpty()) { return this;
} final ImmutableMap<ProductId, PickingJobCandidateProduct> byProductIdNew = byProductId.values() .stream() .map(updater) .collect(ImmutableMap.toImmutableMap(PickingJobCandidateProduct::getProductId, product -> product)); return Objects.equals(this.byProductId, byProductIdNew) ? this : new PickingJobCandidateProducts(byProductIdNew); } @Nullable public ProductId getSingleProductIdOrNull() { return singleProduct != null ? singleProduct.getProductId() : null; } @Nullable public Quantity getSingleQtyToDeliverOrNull() { return singleProduct != null ? singleProduct.getQtyToDeliver() : null; } @Nullable public Quantity getSingleQtyAvailableToPickOrNull() { return singleProduct != null ? singleProduct.getQtyAvailableToPick() : null; } @Nullable public ITranslatableString getSingleProductNameOrNull() { return singleProduct != null ? singleProduct.getProductName() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobCandidateProducts.java
1
请完成以下Java代码
public void setPP_MRP_ID (int PP_MRP_ID) { if (PP_MRP_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_MRP_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_MRP_ID, Integer.valueOf(PP_MRP_ID)); } /** Get Material Requirement Planning. @return Material Requirement Planning */ @Override public int getPP_MRP_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_MRP_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_Order_BOMLine getPP_Order_BOMLine() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_Order_BOMLine_ID, org.eevolution.model.I_PP_Order_BOMLine.class); } @Override public void setPP_Order_BOMLine(org.eevolution.model.I_PP_Order_BOMLine PP_Order_BOMLine) { set_ValueFromPO(COLUMNNAME_PP_Order_BOMLine_ID, org.eevolution.model.I_PP_Order_BOMLine.class, PP_Order_BOMLine); } /** Set Manufacturing Order BOM Line. @param PP_Order_BOMLine_ID Manufacturing Order BOM Line */ @Override public void setPP_Order_BOMLine_ID (int PP_Order_BOMLine_ID) { if (PP_Order_BOMLine_ID < 1) set_Value (COLUMNNAME_PP_Order_BOMLine_ID, null); else set_Value (COLUMNNAME_PP_Order_BOMLine_ID, Integer.valueOf(PP_Order_BOMLine_ID)); } /** Get Manufacturing Order BOM Line. @return Manufacturing Order BOM Line */ @Override public int getPP_Order_BOMLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_BOMLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_Order getPP_Order() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
} @Override public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } /** Set Produktionsauftrag. @param PP_Order_ID Produktionsauftrag */ @Override public void setPP_Order_ID (int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID)); } /** Get Produktionsauftrag. @return Produktionsauftrag */ @Override public int getPP_Order_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP_Alternative.java
1
请完成以下Java代码
public void on(OrderShippedEvent event) { orders.computeIfPresent(event.getOrderId(), (orderId, order) -> { order.setOrderShipped(); emitUpdate(order); return order; }); } @QueryHandler public List<Order> handle(FindAllOrderedProductsQuery query) { return new ArrayList<>(orders.values()); } @QueryHandler public Publisher<Order> handleStreaming(FindAllOrderedProductsQuery query) { return Mono.fromCallable(orders::values) .flatMapMany(Flux::fromIterable); } @QueryHandler public Integer handle(TotalProductsShippedQuery query) { return orders.values() .stream() .filter(o -> o.getOrderStatus() == OrderStatus.SHIPPED) .map(o -> Optional.ofNullable(o.getProducts() .get(query.getProductId())) .orElse(0))
.reduce(0, Integer::sum); } @QueryHandler public Order handle(OrderUpdatesQuery query) { return orders.get(query.getOrderId()); } private void emitUpdate(Order order) { emitter.emit(OrderUpdatesQuery.class, q -> order.getOrderId() .equals(q.getOrderId()), order); } @Override public void reset(List<Order> orderList) { orders.clear(); orderList.forEach(o -> orders.put(o.getOrderId(), o)); } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\querymodel\InMemoryOrdersEventHandler.java
1
请完成以下Spring Boot application配置
app.datasource.url=jdbc:mysql://localhost:3306/numberdb?createDatabaseIfNotExist=true app.datasource.username=root app.datasource.password=root app.datasource.initialization-mode=always app.datasource.platform=mysql app.datasource.initial-pool-size=10 app.datasource.min-pool-size=10 app.datasource.max-pool-size=20 app.datasource.max-idle-time=0 app.datasource.acquire-increment=1 # enable auto-commit (disabled by default) app.datasource.auto-commit-on-close=true # more settings can be added as app.datasou
rce.* spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false spring.jpa.open-in-view=false spring.jpa.hibernate.ddl-auto=none
repos\Hibernate-SpringBoot-master\HibernateSpringBootDataSourceBuilderC3P0Kickoff\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class ClusterNotAvailableException extends RuntimeException { /** * Constructs a new uninitialized instance of {@link ClusterNotAvailableException}. */ public ClusterNotAvailableException() { } /** * Constructs a new instance of {@link ClusterNotAvailableException} initialized with * the given {@link String message} describing the exception. * * @param message {@link String} containing a description of the exception. */ public ClusterNotAvailableException(String message) { super(message); } /** * Constructs a new instance of {@link ClusterNotAvailableException} initialized with * the given {@link Throwable} as the cause of this exception. *
* @param cause {@link Throwable} indicating the cause of this exception. */ public ClusterNotAvailableException(Throwable cause) { super(cause); } /** * Constructs a new instance of {@link ClusterNotAvailableException} initialized with * the given {@link String message} describing the exception along with the given {@link Throwable} * as the cause of this exception. * * @param message {@link String} containing a description of the exception. * @param cause {@link Throwable} indicating the cause of this exception. */ public ClusterNotAvailableException(String message, Throwable cause) { super(message, cause); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterNotAvailableException.java
2
请在Spring Boot框架中完成以下Java代码
public User getUser(Long id) { log.info("获取用户信息"); return restTemplate.getForObject("http://Server-Provider/user/{id}", User.class, id); } @HystrixCommand(fallbackMethod = "getUserDefault2") public User getUserDefault(Long id) { String a = null; // 测试服务降级 a.toString(); User user = new User(); user.setId(-1L); user.setUsername("defaultUser"); user.setPassword("123456"); return user; } public User getUserDefault2(Long id, Throwable e) { System.out.println(e.getMessage()); User user = new User(); user.setId(-2L); user.setUsername("defaultUser2"); user.setPassword("123456"); return user; } public List<User> getUsers() { return this.restTemplate.getForObject("http://Server-Provider/user", List.class); } public String addUser() {
User user = new User(1L, "mrbird", "123456"); HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode(); if (status.is2xxSuccessful()) { return "新增用户成功"; } else { return "新增用户失败"; } } @CacheRemove(commandKey = "getUserById") @HystrixCommand public void updateUser(@CacheKey("id") User user) { this.restTemplate.put("http://Server-Provider/user", user); } public void deleteUser(@PathVariable Long id) { this.restTemplate.delete("http://Server-Provider/user/{1}", id); } }
repos\SpringAll-master\30.Spring-Cloud-Hystrix-Circuit-Breaker\Ribbon-Consumer\src\main\java\com\example\demo\Service\UserService.java
2
请完成以下Java代码
public void setCS_Creditpass_CP_Fallback_ID (int CS_Creditpass_CP_Fallback_ID) { if (CS_Creditpass_CP_Fallback_ID < 1) set_ValueNoCheck (COLUMNNAME_CS_Creditpass_CP_Fallback_ID, null); else set_ValueNoCheck (COLUMNNAME_CS_Creditpass_CP_Fallback_ID, Integer.valueOf(CS_Creditpass_CP_Fallback_ID)); } /** Get CS Creditpass Configuration payment rule fallback. @return CS Creditpass Configuration payment rule fallback */ @Override public int getCS_Creditpass_CP_Fallback_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_CP_Fallback_ID); if (ii == null) return 0; return ii.intValue(); } /** * FallbackPaymentRule AD_Reference_ID=195 * Reference name: _Payment Rule */ public static final int FALLBACKPAYMENTRULE_AD_Reference_ID=195; /** Cash = B */ public static final String FALLBACKPAYMENTRULE_Cash = "B"; /** CreditCard = K */ public static final String FALLBACKPAYMENTRULE_CreditCard = "K"; /** DirectDeposit = T */ public static final String FALLBACKPAYMENTRULE_DirectDeposit = "T"; /** Check = S */ public static final String FALLBACKPAYMENTRULE_Check = "S"; /** OnCredit = P */
public static final String FALLBACKPAYMENTRULE_OnCredit = "P"; /** DirectDebit = D */ public static final String FALLBACKPAYMENTRULE_DirectDebit = "D"; /** Mixed = M */ public static final String FALLBACKPAYMENTRULE_Mixed = "M"; /** Rückerstattung = E */ public static final String PAYMENTRULE_Reimbursement = "E"; /** Verrechnung = F */ public static final String PAYMENTRULE_Settlement = "F"; /** Set Zahlart Rückgriff. @param FallbackPaymentRule Zahlart Rückgriff */ @Override public void setFallbackPaymentRule (java.lang.String FallbackPaymentRule) { set_Value (COLUMNNAME_FallbackPaymentRule, FallbackPaymentRule); } /** Get Zahlart Rückgriff. @return Zahlart Rückgriff */ @Override public java.lang.String getFallbackPaymentRule () { return (java.lang.String)get_Value(COLUMNNAME_FallbackPaymentRule); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_CP_Fallback.java
1
请完成以下Java代码
public CommissionPoints add(@NonNull final CommissionPoints augent) { if (augent.isZero()) { return this; } return CommissionPoints.of(toBigDecimal().add(augent.toBigDecimal())); } public CommissionPoints subtract(@NonNull final CommissionPoints augent) { if (augent.isZero()) { return this; } return CommissionPoints.of(toBigDecimal().subtract(augent.toBigDecimal())); } @JsonIgnore public boolean isZero() { final boolean isZero = points.signum() == 0; return isZero; } public CommissionPoints computePercentageOf( @NonNull final Percent commissionPercent,
final int precision) { final BigDecimal percentagePoints = commissionPercent.computePercentageOf(points, precision); return CommissionPoints.of(percentagePoints); } public CommissionPoints negateIf(final boolean condition) { if (condition) { return CommissionPoints.of(points.negate()); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\CommissionPoints.java
1
请完成以下Java代码
public void setDisableCommand (final @Nullable java.lang.String DisableCommand) { set_Value (COLUMNNAME_DisableCommand, DisableCommand); } @Override public java.lang.String getDisableCommand() { return get_ValueAsString(COLUMNNAME_DisableCommand); } @Override public void setEnableCommand (final @Nullable java.lang.String EnableCommand) { set_Value (COLUMNNAME_EnableCommand, EnableCommand); } @Override public java.lang.String getEnableCommand() { return get_ValueAsString(COLUMNNAME_EnableCommand); } @Override public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class); } @Override public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override
public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setExternalSystem_Service_ID (final int ExternalSystem_Service_ID) { if (ExternalSystem_Service_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, ExternalSystem_Service_ID); } @Override public int getExternalSystem_Service_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Service.java
1
请完成以下Java代码
public void setClassname (java.lang.String Classname) { set_Value (COLUMNNAME_Classname, Classname); } /** Get Java-Klasse. @return Java-Klasse */ @Override public java.lang.String getClassname () { return (java.lang.String)get_Value(COLUMNNAME_Classname); } /** 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); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entitäts-Art. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ @Override public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
/** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** 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\adempiere\pricing\model\X_C_PricingRule.java
1
请完成以下Java代码
public void recordElapsedTime(final long duration, final TimeUnit unit, final Metadata metadata) { final PerformanceMonitoringData perfMonData = getPerformanceMonitoringData(); final ArrayList<Tag> tags = createTags(metadata, perfMonData); try (final IAutoCloseable ignored = perfMonData.addCalledByIfNotNull(metadata)) { final Type effectiveType = perfMonData.getEffectiveType(metadata); final Timer timer = meterRegistry.timer(METER_PREFIX + effectiveType.getCode(), tags); timer.record(duration, unit); } } private static PerformanceMonitoringData getPerformanceMonitoringData() { if (perfMonDataTL.get() == null) { perfMonDataTL.set(new PerformanceMonitoringData()); } return perfMonDataTL.get(); } @NonNull private static ArrayList<Tag> createTags(final @NonNull Metadata metadata, final PerformanceMonitoringData perfMonData) { final ArrayList<Tag> tags = new ArrayList<>(); addTagIfNotNull("name", metadata.getClassName(), tags); addTagIfNotNull("action", metadata.getFunctionName(), tags); if (!perfMonData.isInitiator()) { addTagIfNotNull("depth", String.valueOf(perfMonData.getDepth()), tags); addTagIfNotNull("initiator", perfMonData.getInitiatorFunctionNameFQ(), tags); addTagIfNotNull("window", perfMonData.getInitiatorWindow(), tags); addTagIfNotNull("callerName", metadata.getFunctionNameFQ(), tags); addTagIfNotNull("calledBy", perfMonData.getLastCalledFunctionNameFQ(), tags); } else {
for (final Entry<String, String> entry : metadata.getLabels().entrySet()) { if (PerformanceMonitoringService.VOLATILE_LABELS.contains(entry.getKey())) { // Avoid OOME: if we included e.g. the recordId, then every recordId would cause a new meter to be created. continue; } addTagIfNotNull(entry.getKey(), entry.getValue(), tags); } } return tags; } private static void addTagIfNotNull(@Nullable final String name, @Nullable final String value, @NonNull final ArrayList<Tag> tags) { final String nameNorm = StringUtils.trimBlankToNull(name); if (nameNorm == null) { return; } final String valueNorm = StringUtils.trimBlankToNull(value); if (valueNorm == null) { return; } tags.add(Tag.of(nameNorm, valueNorm)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\adapter\MicrometerPerformanceMonitoringService.java
1
请完成以下Java代码
private static Collection<ExposableWebEndpoint> asList(@Nullable ExposableWebEndpoint healthEndpoint) { return (healthEndpoint != null) ? Collections.singletonList(healthEndpoint) : Collections.emptyList(); } @Override protected void initHandlerMethods() { if (this.healthEndpoint == null) { return; } for (WebOperation operation : this.healthEndpoint.getOperations()) { WebOperationRequestPredicate predicate = operation.getRequestPredicate(); String matchAllRemainingPathSegmentsVariable = predicate.getMatchAllRemainingPathSegmentsVariable(); if (matchAllRemainingPathSegmentsVariable != null) { for (HealthEndpointGroup group : this.groups) { AdditionalHealthEndpointPath additionalPath = group.getAdditionalPath(); if (additionalPath != null) { RequestMappingInfo requestMappingInfo = getRequestMappingInfo(operation, additionalPath.getValue()); registerReadMapping(requestMappingInfo, this.healthEndpoint, operation); } } } }
} private RequestMappingInfo getRequestMappingInfo(WebOperation operation, String additionalPath) { WebOperationRequestPredicate predicate = operation.getRequestPredicate(); String path = this.endpointMapping.createSubPath(additionalPath); RequestMethod method = RequestMethod.valueOf(predicate.getHttpMethod().name()); String[] consumes = StringUtils.toStringArray(predicate.getConsumes()); String[] produces = StringUtils.toStringArray(predicate.getProduces()); return RequestMappingInfo.paths(path).methods(method).consumes(consumes).produces(produces).build(); } @Override protected LinksHandler getLinksHandler() { return (exchange) -> Mono.empty(); } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\endpoint\web\AdditionalHealthEndpointPathsWebFluxHandlerMapping.java
1
请完成以下Java代码
protected static JsonNode convertToJsonCaseInstanceVariables(CaseInstanceMigrationDocument caseInstanceMigrationDocument, ObjectMapper objectMapper) { Map<String, Object> caseInstanceVariables = caseInstanceMigrationDocument.getCaseInstanceVariables(); if (caseInstanceVariables != null && !caseInstanceVariables.isEmpty()) { return objectMapper.valueToTree(caseInstanceVariables); } return null; } protected static <T> T convertFromJsonNodeToObject(JsonNode jsonNode, ObjectMapper objectMapper) { return objectMapper.convertValue(jsonNode, new TypeReference<>() { }); } protected static String getJsonProperty(String propertyName, JsonNode jsonNode) { if (jsonNode.has(propertyName) && !jsonNode.get(propertyName).isNull()) { return jsonNode.get(propertyName).asString(); } return null; } protected static Integer getJsonPropertyAsInteger(String propertyName, JsonNode jsonNode) {
if (jsonNode.has(propertyName) && !jsonNode.get(propertyName).isNull()) { return jsonNode.get(propertyName).asInt(); } return null; } protected static <V> V getLocalVariablesFromJson(JsonNode jsonNode, ObjectMapper objectMapper) { JsonNode localVariablesNode = jsonNode.get(LOCAL_VARIABLES_JSON_SECTION); if (localVariablesNode != null) { return convertFromJsonNodeToObject(localVariablesNode, objectMapper); } return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationDocumentConverter.java
1
请完成以下Java代码
public class InstantRestVariableConverter implements RestVariableConverter { @Override public String getRestTypeName() { return "instant"; } @Override public Class<?> getVariableType() { return Instant.class; } @Override public Object getVariableValue(EngineRestVariable result) { if (result.getValue() != null) { if (!(result.getValue() instanceof String)) { throw new FlowableIllegalArgumentException("Converter can only convert string to instant"); } try { return Instant.parse((String) result.getValue()); } catch (DateTimeParseException e) { throw new FlowableIllegalArgumentException("The given variable value is not an instant: '" + result.getValue() + "'", e);
} } return null; } @Override public void convertVariableValue(Object variableValue, EngineRestVariable result) { if (variableValue != null) { if (!(variableValue instanceof Instant)) { throw new FlowableIllegalArgumentException("Converter can only convert instant"); } result.setValue(variableValue.toString()); } else { result.setValue(null); } } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\InstantRestVariableConverter.java
1
请完成以下Java代码
public String toJson() { return code; } /** * Accepts either the human-readable constant name (e.g. "PublicInformation") or the code (e.g. "A"). */ @JsonCreator public static JsonConfidentialType fromJson(final String value) { if (value == null) { return null; } // Try by code first for (final JsonConfidentialType t : values()) { if (t.code.equalsIgnoreCase(value)) {
return t; } } // Then by enum name (human-readable constant without the generated prefix) for (final JsonConfidentialType t : values()) { if (t.name().equalsIgnoreCase(value)) { return t; } } throw new IllegalArgumentException("Unknown ConfidentialType: " + value); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\request\JsonConfidentialType.java
1
请完成以下Java代码
protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected JobDefinitionQuery createNewQuery(ProcessEngine engine) { return engine.getManagementService().createJobDefinitionQuery(); } @Override protected void applyFilters(JobDefinitionQuery query) { if (jobDefinitionId != null) { query.jobDefinitionId(jobDefinitionId); } if (activityIdIn != null && activityIdIn.length > 0) { query.activityIdIn(activityIdIn); } if (processDefinitionId != null) { query.processDefinitionId(processDefinitionId); } if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } if (jobType != null) { query.jobType(jobType); } if (jobConfiguration != null) { query.jobConfiguration(jobConfiguration); } if (TRUE.equals(active)) { query.active(); } if (TRUE.equals(suspended)) { query.suspended();
} if (TRUE.equals(withOverridingJobPriority)) { query.withOverridingJobPriority(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeJobDefinitionsWithoutTenantId)) { query.includeJobDefinitionsWithoutTenantId(); } } @Override protected void applySortBy(JobDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_JOB_DEFINITION_ID)) { query.orderByJobDefinitionId(); } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { query.orderByActivityId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_JOB_TYPE)) { query.orderByJobType(); } else if (sortBy.equals(SORT_BY_JOB_CONFIGURATION)) { query.orderByJobConfiguration(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\management\JobDefinitionQueryDto.java
1
请完成以下Java代码
public UserQuery memberOfGroup(String groupId) { ensureNotNull("Provided groupId", groupId); this.groupId = groupId; return this; } public UserQuery potentialStarter(String procDefId) { ensureNotNull("Provided processDefinitionId", procDefId); this.procDefId = procDefId; return this; } public UserQuery memberOfTenant(String tenantId) { ensureNotNull("Provided tenantId", tenantId); this.tenantId = tenantId; return this; } //sorting ////////////////////////////////////////////////////////// public UserQuery orderByUserId() { return orderBy(UserQueryProperty.USER_ID); } public UserQuery orderByUserEmail() { return orderBy(UserQueryProperty.EMAIL); } public UserQuery orderByUserFirstName() { return orderBy(UserQueryProperty.FIRST_NAME); } public UserQuery orderByUserLastName() { return orderBy(UserQueryProperty.LAST_NAME); } //getters ////////////////////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getFirstName() { return firstName; } public String getFirstNameLike() {
return firstNameLike; } public String getLastName() { return lastName; } public String getLastNameLike() { return lastNameLike; } public String getEmail() { return email; } public String getEmailLike() { return emailLike; } public String getGroupId() { return groupId; } public String getTenantId() { return tenantId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserQueryImpl.java
1
请完成以下Java代码
public void dispose() { if (m_gridController != null) { m_gridController.dispose(); } m_gridController = null; super.dispose(); orgField = null; locatorField = null; productField = null; mtypeField = null; dateFField = null; dateTField = null; // if (m_frame != null) { m_frame.dispose(); } m_frame = null; } // dispose /************************************************************************** * Action Listener * @param e event */ @Override public void actionPerformed (ActionEvent e) { if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) { dispose(); } else if (e.getActionCommand().equals(ConfirmPanel.A_REFRESH) || e.getActionCommand().equals(ConfirmPanel.A_OK)) { refresh(); } else if (e.getActionCommand().equals(ConfirmPanel.A_ZOOM)) { zoom(); } } // actionPerformed /************************************************************************** * Property Listener * @param e event */ @Override public void vetoableChange (PropertyChangeEvent e) { final String propertyName = e.getPropertyName(); if (I_M_Transaction.COLUMNNAME_M_Product_ID.equals(propertyName)) { productField.setValue(e.getNewValue()); } else if (I_M_Transaction.COLUMNNAME_C_BPartner_ID.equals(propertyName)) { bpartnerField.setValue(e.getNewValue()); }
} // vetoableChange public void setProductFieldValue(final Object value) { productField.setValue(value); refresh(); } public void setDate(final Timestamp date) { dateFField.setValue(date); dateTField.setValue(date); refresh(); } /************************************************************************** * Refresh - Create Query and refresh grid */ private void refresh() { final Object organization = orgField.getValue(); final Object locator = locatorField.getValue(); final Object product = productField.getValue(); final Object movementType = mtypeField.getValue(); final Timestamp movementDateFrom = dateFField.getValue(); final Timestamp movementDateTo = dateTField.getValue(); final Object bpartnerId = bpartnerField.getValue(); Services.get(IClientUI.class).executeLongOperation(panel, () -> refresh(organization, locator, product, movementType, movementDateFrom, movementDateTo, bpartnerId, statusBar)); } // refresh /** * Zoom */ @Override public void zoom() { super.zoom(); // Zoom panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); AWindow frame = new AWindow(); if (!frame.initWindow(adWindowId, query)) { panel.setCursor(Cursor.getDefaultCursor()); return; } AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; panel.setCursor(Cursor.getDefaultCursor()); } // zoom } // VTrxMaterial
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTrxMaterial.java
1
请完成以下Java代码
public void destroy() { log.debug("[{}] Stopping generator", originatorId); initialized.set(false); prevMsg = null; nextTickId = null; lastScheduledTs = 0; if (scriptEngine != null) { scriptEngine.destroy(); scriptEngine = null; } } @Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { boolean hasChanges = false; switch (fromVersion) { case 0: if (oldConfiguration.has(QUEUE_NAME)) { hasChanges = true; ((ObjectNode) oldConfiguration).remove(QUEUE_NAME); } case 1: String originatorType = "originatorType";
String originatorId = "originatorId"; boolean hasType = oldConfiguration.hasNonNull(originatorType); boolean hasOriginatorId = oldConfiguration.hasNonNull(originatorId) && StringUtils.isNotBlank(oldConfiguration.get(originatorId).asText()); boolean hasOriginatorFields = hasType && hasOriginatorId; if (!hasOriginatorFields) { hasChanges = true; ((ObjectNode) oldConfiguration).put(originatorType, EntityType.RULE_NODE.name()); } break; default: break; } return new TbPair<>(hasChanges, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\debug\TbMsgGeneratorNode.java
1
请完成以下Java代码
private boolean findLeakedPassword(List<String> passwords, String suffix) { for (String pw : passwords) { if (pw.startsWith(suffix)) { return true; } } return false; } private List<String> getLeakedPasswordsForPrefix(String prefix) { try { String response = this.restClient.get().uri(prefix).retrieve().body(String.class); if (!StringUtils.hasText(response)) { return Collections.emptyList(); } return response.lines().toList(); }
catch (RestClientException ex) { this.logger.error("Request for leaked passwords failed", ex); return Collections.emptyList(); } } private static MessageDigest getSha1Digest() { try { return MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex.getMessage()); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\password\HaveIBeenPwnedRestApiPasswordChecker.java
1
请完成以下Java代码
protected void prepare() { for (final ProcessInfoParameter para : getParametersAsArray()) { if (para.getParameter() == null) { // skip if no parameter value continue; } final String name = para.getParameterName(); if (name.equals(PARAM_IsAutoProcess)) { p_isAutoProcess = para.getParameterAsBoolean(); } } } @Override protected String doIt() { final IDunningBL dunningBL = Services.get(IDunningBL.class); final IDunningContext context = dunningBL.createDunningContext(getCtx(), null, // DunningDate, not needed null, // C_DunningLevel, not needed get_TrxName()); context.setProperty(IDunningProducer.CONTEXT_ProcessDunningDoc, p_isAutoProcess); // // Create Async Batch for tracking // retrieve async batch type final I_C_Async_Batch_Type asyncBatchType; asyncBatchType = asyncBatchDAO.retrieveAsyncBatchType(getCtx(), m_asyncBatchType); Check.assumeNotNull(asyncBatchType, "Defined Async Batch type should not be null for internal name ", m_asyncBatchType); // Create Async Batch for tracking final AsyncBatchId asyncBatchId = asyncBatchBL.newAsyncBatch() .setContext(getCtx()) .setC_Async_Batch_Type(asyncBatchType.getInternalName()) .setAD_PInstance_Creator_ID(getPinstanceId()) .setName(m_AsyncBatchName) .setDescription(m_AsyncBatchDesc) .buildAndEnqueue(); context.setProperty(IDunningProducer.CONTEXT_AsyncBatchIdDunningDoc, asyncBatchId); final SelectedDunningCandidatesSource source = new SelectedDunningCandidatesSource(getProcessInfo().getWhereClause()); source.setDunningContext(context); dunningBL.processCandidates(context, source); return MSG_OK; }
/** * This dunning candidate source returns only those candidates that have been selected by the user. */ private static final class SelectedDunningCandidatesSource extends AbstractDunningCandidateSource { private final String whereClause; public SelectedDunningCandidatesSource(final String whereClause) { this.whereClause = whereClause; } @Override public Iterator<I_C_Dunning_Candidate> iterator() { final IDunningDAO dunningDAO = Services.get(IDunningDAO.class); final Iterator<I_C_Dunning_Candidate> it = dunningDAO.retrieveNotProcessedCandidatesIteratorRW(getDunningContext(), whereClause); return it; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_Dunning_Candidate_Process.java
1
请完成以下Java代码
private static final void updateM_AttributeSet(final int attributeSetId) { // TODO: translate it to Query API // Update M_AttributeSet.IsInstanceAttribute='Y' { final String sql = "UPDATE M_AttributeSet mas" + " SET IsInstanceAttribute='Y' " + "WHERE M_AttributeSet_ID=" + attributeSetId + " AND IsInstanceAttribute='N'" + " AND (EXISTS (SELECT * FROM M_AttributeUse mau" + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) " + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID" + " AND mau.IsActive='Y' AND ma.IsActive='Y'" + " AND ma.IsInstanceAttribute='Y')" + ")"; DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); } // Update M_AttributeSet.IsInstanceAttribute='N' { final String sql = "UPDATE M_AttributeSet mas" + " SET IsInstanceAttribute='N' " + "WHERE M_AttributeSet_ID=" + attributeSetId + " AND IsInstanceAttribute='Y'"
+ " AND NOT EXISTS (SELECT * FROM M_AttributeUse mau" + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) " + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID" + " AND mau.IsActive='Y' AND ma.IsActive='Y'" + " AND ma.IsInstanceAttribute='Y')"; DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); } } @Override protected boolean afterSave(final boolean newRecord, final boolean success) { updateM_AttributeSet(getM_AttributeSet_ID()); return success; } @Override protected boolean afterDelete(final boolean success) { updateM_AttributeSet(getM_AttributeSet_ID()); return success; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAttributeUse.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Nutrition Fact. @param M_Nutrition_Fact_ID Nutrition Fact */ @Override public void setM_Nutrition_Fact_ID (int M_Nutrition_Fact_ID) { if (M_Nutrition_Fact_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Nutrition_Fact_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Nutrition_Fact_ID, Integer.valueOf(M_Nutrition_Fact_ID)); } /** Get Nutrition Fact. @return Nutrition Fact */ @Override public int getM_Nutrition_Fact_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_M_Nutrition_Fact_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Nutrition_Fact.java
1
请在Spring Boot框架中完成以下Java代码
private JsonAttachment buildJsonAttachment(@NonNull final de.metas.camel.externalsystems.grssignum.to_grs.api.model.JsonAttachment attachment) { return JsonAttachmentUtil.createLocalFileJsonAttachment( "", attachment.getFileName(), buildJsonTags(attachment)); } @NonNull private ImmutableList<JsonTag> buildJsonTags(@NonNull final de.metas.camel.externalsystems.grssignum.to_grs.api.model.JsonAttachment attachment) { final ImmutableList.Builder<JsonTag> jsonTagBuilder = ImmutableList.builder(); jsonTagBuilder.add(JsonTag.of(AttachmentTags.ID.getName(), attachment.getId())); if (Check.isNotBlank(attachment.getValidUntil())) {
jsonTagBuilder.add(JsonTag.of(AttachmentTags.VALID_TO.getName(), attachment.getValidUntil())); } if (Check.isNotBlank(attachment.getDocumentType())) { jsonTagBuilder.add(JsonTag.of(AttachmentTags.DOCUMENT_TYPE.getName(), attachment.getDocumentType())); } if (Check.isNotBlank(attachment.getDocumentGroup())) { jsonTagBuilder.add(JsonTag.of(AttachmentTags.DOCUMENT_GROUP.getName(), attachment.getDocumentGroup())); } return jsonTagBuilder.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\product\processor\RawMaterialAttachFileProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public class HistoricTaskLogEntryQueryProperty implements QueryProperty { private static final long serialVersionUID = 1L; private static final Map<String, HistoricTaskLogEntryQueryProperty> properties = new HashMap<>(); public static final HistoricTaskLogEntryQueryProperty LOG_NUMBER = new HistoricTaskLogEntryQueryProperty("RES.ID_"); public static final HistoricTaskLogEntryQueryProperty TYPE = new HistoricTaskLogEntryQueryProperty("RES.TYPE_"); public static final HistoricTaskLogEntryQueryProperty TASK_ID_ = new HistoricTaskLogEntryQueryProperty("RES.TASK_ID_"); public static final HistoricTaskLogEntryQueryProperty TIME_STAMP = new HistoricTaskLogEntryQueryProperty("RES.TIME_STAMP_"); public static final HistoricTaskLogEntryQueryProperty USER_ID = new HistoricTaskLogEntryQueryProperty("RES.USER_ID"); public static final HistoricTaskLogEntryQueryProperty DATA = new HistoricTaskLogEntryQueryProperty("RES.DATA_"); public static final HistoricTaskLogEntryQueryProperty EXECUTION_ID = new HistoricTaskLogEntryQueryProperty("RES.EXECUTION_ID_"); public static final HistoricTaskLogEntryQueryProperty PROCESS_INSTANCE_ID = new HistoricTaskLogEntryQueryProperty("RES.PROC_INST_ID_"); public static final HistoricTaskLogEntryQueryProperty PROCESS_DEFINITION_ID = new HistoricTaskLogEntryQueryProperty("RES.PROC_DEF_ID_"); public static final HistoricTaskLogEntryQueryProperty SCOPE_ID = new HistoricTaskLogEntryQueryProperty("RES.SCOPE_ID_"); public static final HistoricTaskLogEntryQueryProperty SCOPE_DEFINITION_ID = new HistoricTaskLogEntryQueryProperty("RES.SCOPE_DEFINITION_ID_"); public static final HistoricTaskLogEntryQueryProperty SUB_SCOPE_ID = new HistoricTaskLogEntryQueryProperty("RES.SUB_SCOPE_ID_"); public static final HistoricTaskLogEntryQueryProperty SCOPE_TYPE = new HistoricTaskLogEntryQueryProperty("RES.SCOPE_TYPE_");
public static final HistoricTaskLogEntryQueryProperty TENANT_ID = new HistoricTaskLogEntryQueryProperty("RES.TENANT_ID_"); private String name; public HistoricTaskLogEntryQueryProperty(String name) { this.name = name; properties.put(name, this); } @Override public String getName() { return name; } public static HistoricTaskLogEntryQueryProperty findByName(String propertyName) { return properties.get(propertyName); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskLogEntryQueryProperty.java
2
请在Spring Boot框架中完成以下Java代码
public class TraceableObject<O, C> { protected MutableVariableType<O, C> type; protected O tracedObject; protected C tracedObjectOriginalValue; protected VariableInstanceEntity variableInstanceEntity; public TraceableObject(MutableVariableType<O, C> type, O tracedObject, C tracedObjectOriginalValue, VariableInstanceEntity variableInstanceEntity) { this.type = type; this.tracedObject = tracedObject; this.tracedObjectOriginalValue = tracedObjectOriginalValue; this.variableInstanceEntity = variableInstanceEntity; } public void updateIfValueChanged() { if (tracedObject == variableInstanceEntity.getCachedValue()) { if (type.updateValueIfChanged(tracedObject, tracedObjectOriginalValue, variableInstanceEntity)) { VariableServiceConfiguration variableServiceConfiguration = getVariableServiceConfiguration(); variableServiceConfiguration.getInternalHistoryVariableManager().recordVariableUpdate( variableInstanceEntity, variableServiceConfiguration.getClock().getCurrentTime()); } } } protected VariableServiceConfiguration getVariableServiceConfiguration() { String engineType = getEngineType(variableInstanceEntity.getScopeType()); Map<String, AbstractEngineConfiguration> engineConfigurationMap = Context.getCommandContext().getEngineConfigurations(); AbstractEngineConfiguration engineConfiguration = engineConfigurationMap.get(engineType); if (engineConfiguration == null) { for (AbstractEngineConfiguration possibleEngineConfiguration : engineConfigurationMap.values()) { if (possibleEngineConfiguration instanceof HasVariableServiceConfiguration) { engineConfiguration = possibleEngineConfiguration; } }
} if (engineConfiguration == null) { throw new FlowableException("Could not find engine configuration with variable service configuration"); } if (!(engineConfiguration instanceof HasVariableServiceConfiguration)) { throw new FlowableException("Variable entity engine scope has no variable service configuration " + engineType); } return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG); } protected String getEngineType(String scopeType) { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\TraceableObject.java
2
请完成以下Java代码
public static synchronized void destroy() { if (isInitialized()) { Map<String, CmmnEngine> engines = new HashMap<>(cmmnEngines); cmmnEngines = new HashMap<>(); for (String cmmnEngineName : engines.keySet()) { CmmnEngine cmmnEngine = engines.get(cmmnEngineName); try { cmmnEngine.close(); } catch (Exception e) { LOGGER.error("exception while closing {}", (cmmnEngineName == null ? "the default cmmn engine" : "cmmn engine " + cmmnEngineName), e); } } cmmnEngineInfosByName.clear();
cmmnEngineInfosByResourceUrl.clear(); cmmnEngineInfos.clear(); setInitialized(false); } } public static boolean isInitialized() { return isInitialized; } public static void setInitialized(boolean isInitialized) { CmmnEngines.isInitialized = isInitialized; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngines.java
1
请在Spring Boot框架中完成以下Java代码
public class BatchJdbcProperties extends DatabaseInitializationProperties { private static final String DEFAULT_SCHEMA_LOCATION = "classpath:org/springframework/" + "batch/core/schema-@@platform@@.sql"; /** * Whether to validate the transaction state. */ private boolean validateTransactionState = true; /** * Transaction isolation level to use when creating job meta-data for new jobs. */ private @Nullable Isolation isolationLevelForCreate; /** * Table prefix for all the batch meta-data tables. */ private @Nullable String tablePrefix; public boolean isValidateTransactionState() { return this.validateTransactionState; } public void setValidateTransactionState(boolean validateTransactionState) {
this.validateTransactionState = validateTransactionState; } public @Nullable Isolation getIsolationLevelForCreate() { return this.isolationLevelForCreate; } public void setIsolationLevelForCreate(@Nullable Isolation isolationLevelForCreate) { this.isolationLevelForCreate = isolationLevelForCreate; } public @Nullable String getTablePrefix() { return this.tablePrefix; } public void setTablePrefix(@Nullable String tablePrefix) { this.tablePrefix = tablePrefix; } @Override public String getDefaultSchemaLocation() { return DEFAULT_SCHEMA_LOCATION; } }
repos\spring-boot-4.0.1\module\spring-boot-batch-jdbc\src\main\java\org\springframework\boot\batch\jdbc\autoconfigure\BatchJdbcProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class SupplyRequiredHandlerHelper { private static final Logger logger = LogManager.getLogger(SupplyRequiredHandlerHelper.class); @NonNull private final IOrgDAO orgDAO = Services.get(IOrgDAO.class); @NonNull private final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class); @NonNull private final IProductPlanningDAO productPlanningDAO = Services.get(IProductPlanningDAO.class); @Nullable protected MaterialPlanningContext createContextOrNull(@NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor) { final OrgId orgId = supplyRequiredDescriptor.getOrgId(); final WarehouseId warehouseId = supplyRequiredDescriptor.getWarehouseId(); final I_M_Warehouse warehouse = warehouseDAO.getById(warehouseId); final ProductId productId = ProductId.ofRepoId(supplyRequiredDescriptor.getProductId()); final AttributeSetInstanceId attributeSetInstanceId = AttributeSetInstanceId.ofRepoIdOrNone(supplyRequiredDescriptor.getAttributeSetInstanceId()); final ResourceId plantId = productPlanningDAO.findPlantIfExists(orgId, warehouse, productId, attributeSetInstanceId).orElse(null); if (plantId == null) { Loggables.withLogger(logger, Level.DEBUG).addLog("No plant found for {}, {}, {}, {}", orgId, warehouse, productId, attributeSetInstanceId); return null; } final ProductPlanningQuery productPlanningQuery = ProductPlanningQuery.builder() .orgId(orgId) .warehouseId(warehouseId) .plantId(plantId) .productId(productId) .includeWithNullProductId(false) .attributeSetInstanceId(attributeSetInstanceId) .build(); final ProductPlanning productPlanning = productPlanningDAO.find(productPlanningQuery).orElse(null); if (productPlanning == null) {
Loggables.withLogger(logger, Level.DEBUG).addLog("No PP_Product_Planning record found => nothing to do; query={}", productPlanningQuery); return null; } final I_AD_Org org = orgDAO.getById(orgId); return MaterialPlanningContext.builder() .productId(productId) .attributeSetInstanceId(attributeSetInstanceId) .warehouseId(warehouseId) .productPlanning(productPlanning) .plantId(plantId) .clientAndOrgId(ClientAndOrgId.ofClientAndOrg(org.getAD_Client_ID(), org.getAD_Org_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredHandlerHelper.java
2
请完成以下Java代码
public Builder keys(List<String> keys) { this.keys = keys; return this; } public Builder deleteHistoryQueries(List<DeleteTsKvQuery> deleteHistoryQueries) { this.deleteHistoryQueries = deleteHistoryQueries; return this; } public Builder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = previousCalculatedFieldIds; return this; } public Builder tbMsgId(UUID tbMsgId) { this.tbMsgId = tbMsgId; return this; } public Builder tbMsgType(TbMsgType tbMsgType) {
this.tbMsgType = tbMsgType; return this; } public Builder callback(FutureCallback<List<String>> callback) { this.callback = callback; return this; } public TimeseriesDeleteRequest build() { return new TimeseriesDeleteRequest(tenantId, entityId, keys, deleteHistoryQueries, previousCalculatedFieldIds, tbMsgId, tbMsgType, callback); } } }
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\TimeseriesDeleteRequest.java
1
请完成以下Java代码
class JdbcAdaptingLiquibaseConnectionDetailsFactory implements ConnectionDetailsFactory<JdbcConnectionDetails, LiquibaseConnectionDetails> { @Override public LiquibaseConnectionDetails getConnectionDetails(JdbcConnectionDetails input) { return new LiquibaseConnectionDetails() { @Override public @Nullable String getUsername() { return input.getUsername(); } @Override public @Nullable String getPassword() { return input.getPassword(); }
@Override public String getJdbcUrl() { return input.getJdbcUrl(); } @Override public String getDriverClassName() { return input.getDriverClassName(); } }; } }
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\docker\compose\JdbcAdaptingLiquibaseConnectionDetailsFactory.java
1
请完成以下Java代码
public String getHstsValue() { return hstsValue; } public void setHstsValue(String hstsValue) { this.hstsValue = hstsValue; } public String getHstsMaxAge() { return hstsMaxAge; } public void setHstsMaxAge(String hstsMaxAge) { this.hstsMaxAge = hstsMaxAge; } @Override public String toString() { StringJoiner joinedString = joinOn(this.getClass())
.add("xssProtectionDisabled=" + xssProtectionDisabled) .add("xssProtectionOption=" + xssProtectionOption) .add("xssProtectionValue=" + xssProtectionValue) .add("contentSecurityPolicyDisabled=" + contentSecurityPolicyDisabled) .add("contentSecurityPolicyValue=" + contentSecurityPolicyValue) .add("contentTypeOptionsDisabled=" + contentTypeOptionsDisabled) .add("contentTypeOptionsValue=" + contentTypeOptionsValue) .add("hstsDisabled=" + hstsDisabled) .add("hstsMaxAge=" + hstsMaxAge) .add("hstsIncludeSubdomainsDisabled=" + hstsIncludeSubdomainsDisabled) .add("hstsValue=" + hstsValue); return joinedString.toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\HeaderSecurityProperties.java
1
请完成以下Java代码
public void onResume(CmmnActivityExecution execution) { ensureNotCaseInstance(execution, "resume"); ensureTransitionAllowed(execution, SUSPENDED, ACTIVE, "resume"); CmmnActivityExecution parent = execution.getParent(); if (parent != null) { if (!parent.isActive()) { String id = execution.getId(); throw LOG.resumeInactiveCaseException("resume", id); } } resuming(execution); } public void onParentResume(CmmnActivityExecution execution) { ensureNotCaseInstance(execution, "parentResume"); String id = execution.getId(); if (!execution.isSuspended()) { throw LOG.wrongCaseStateException("parentResume", id, "resume", "suspended", execution.getCurrentState().toString()); } CmmnActivityExecution parent = execution.getParent(); if (parent != null) { if (!parent.isActive()) { throw LOG.resumeInactiveCaseException("parentResume", id); } } resuming(execution); } // occur //////////////////////////////////////////////////////// public void onOccur(CmmnActivityExecution execution) { String id = execution.getId(); throw LOG.illegalStateTransitionException("occur", id, getTypeName()); } // sentry /////////////////////////////////////////////////////////////// public void fireEntryCriteria(CmmnActivityExecution execution) { boolean manualActivation = evaluateManualActivationRule(execution); if (manualActivation) { execution.enable();
} else { execution.start(); } } // manual activation rule ////////////////////////////////////////////// protected boolean evaluateManualActivationRule(CmmnActivityExecution execution) { boolean manualActivation = false; CmmnActivity activity = execution.getActivity(); Object manualActivationRule = activity.getProperty(PROPERTY_MANUAL_ACTIVATION_RULE); if (manualActivationRule != null) { CaseControlRule rule = (CaseControlRule) manualActivationRule; manualActivation = rule.evaluate(execution); } return manualActivation; } // helper /////////////////////////////////////////////////////////// protected abstract String getTypeName(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\StageOrTaskActivityBehavior.java
1
请完成以下Java代码
public void setR_RequestUpdate_ID (int R_RequestUpdate_ID) { if (R_RequestUpdate_ID < 1) set_ValueNoCheck (COLUMNNAME_R_RequestUpdate_ID, null); else set_ValueNoCheck (COLUMNNAME_R_RequestUpdate_ID, Integer.valueOf(R_RequestUpdate_ID)); } /** Get Request Update. @return Request Updates */ public int getR_RequestUpdate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestUpdate_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair()
{ return new KeyNamePair(get_ID(), String.valueOf(getR_RequestUpdate_ID())); } /** Set Start Time. @param StartTime Time started */ public void setStartTime (Timestamp StartTime) { set_Value (COLUMNNAME_StartTime, StartTime); } /** Get Start Time. @return Time started */ public Timestamp getStartTime () { return (Timestamp)get_Value(COLUMNNAME_StartTime); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestUpdate.java
1
请完成以下Java代码
public boolean isAllowTrxAfterThreadEnd() { return allowTrxAfterThreadEnd; } @Override public void reset() { setActive(DEFAULT_ACTIVE); setAllowTrxAfterThreadEnd(DEFAULT_ALLOW_TRX_AFTER_TREAD_END); setMaxSavepoints(DEFAULT_MAX_SAVEPOINTS); setMaxTrx(DEFAULT_MAX_TRX); setTrxTimeoutSecs(DEFAULT_TRX_TIMEOUT_SECS, DEFAULT_TRX_TIMEOUT_LOG_ONLY); setOnlyAllowedTrxNamePrefixes(DEFAULT_ONLY_ALLOWED_TRXNAME_PREFIXES); allowedTrxNamePrefixes.clear(); } @Override
public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("TrxConstraints["); sb.append("active=" + this.active); sb.append(", allowedTrxNamePrefixes=" + getAllowedTrxNamePrefixes()); sb.append(", allowTrxAfterThreadEnd=" + isAllowTrxAfterThreadEnd()); sb.append(", maxSavepoints=" + getMaxSavepoints()); sb.append(", maxTrx=" + getMaxTrx()); sb.append(", onlyAllowedTrxNamePrefixes=" + isOnlyAllowedTrxNamePrefixes()); sb.append(", trxTimeoutLogOnly=" + isTrxTimeoutLogOnly()); sb.append(", trxTimeoutSecs=" + getTrxTimeoutSecs()); sb.append("]"); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraints.java
1
请完成以下Java代码
public static AttributeCode extractAttributeCode(final org.compiere.model.I_M_Attribute attribute) { return AttributeCode.ofString(attribute.getValue()); } public static Object extractJSONValue( @NonNull final IAttributeStorage attributesStorage, @NonNull final IAttributeValue attributeValue, @NonNull final JSONOptions jsonOpts) { final Object value = extractValueAndResolve(attributesStorage, attributeValue); return Values.valueToJsonObject(value, jsonOpts); } @Nullable private static Object extractValueAndResolve( @NonNull final IAttributeStorage attributesStorage, @NonNull final IAttributeValue attributeValue) { final Object value = attributeValue.getValue(); if (!attributeValue.isList()) { return value; } final IAttributeValuesProvider valuesProvider = attributeValue.getAttributeValuesProvider(); final Evaluatee evalCtx = valuesProvider.prepareContext(attributesStorage); final NamePair valueNP = valuesProvider.getAttributeValueOrNull(evalCtx, value); final TooltipType tooltipType = Services.get(IADTableDAO.class).getTooltipTypeByTableName(I_M_Attribute.Table_Name); return LookupValue.fromNamePair(valueNP, null, tooltipType); } public static DocumentFieldWidgetType extractWidgetType(final IAttributeValue attributeValue) { if (attributeValue.isList()) { final I_M_Attribute attribute = attributeValue.getM_Attribute(); if (attribute.isHighVolume()) { return DocumentFieldWidgetType.Lookup; } else { return DocumentFieldWidgetType.List; } } else if (attributeValue.isStringValue()) { return DocumentFieldWidgetType.Text; } else if (attributeValue.isNumericValue()) { return DocumentFieldWidgetType.Number; } else if (attributeValue.isDateValue())
{ return DocumentFieldWidgetType.LocalDate; } else { throw new IllegalArgumentException("Cannot extract widgetType from " + attributeValue); } } @NonNull private static Optional<DocumentLayoutElementDescriptor> getClearanceNoteLayoutElement(@NonNull final I_M_HU hu) { if (Check.isBlank(hu.getClearanceNote())) { return Optional.empty(); } final boolean isDisplayedClearanceStatus = Services.get(ISysConfigBL.class).getBooleanValue(SYS_CONFIG_CLEARANCE, true); if (!isDisplayedClearanceStatus) { return Optional.empty(); } return Optional.of(createClearanceNoteLayoutElement()); } @NonNull private static DocumentLayoutElementDescriptor createClearanceNoteLayoutElement() { final ITranslatableString caption = Services.get(IMsgBL.class).translatable(I_M_HU.COLUMNNAME_ClearanceNote); return DocumentLayoutElementDescriptor.builder() .setCaption(caption) .setWidgetType(DocumentFieldWidgetType.Text) .addField(DocumentLayoutElementFieldDescriptor .builder(I_M_HU.COLUMNNAME_ClearanceNote) .setPublicField(true)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributesHelper.java
1
请完成以下Java代码
public void run(Properties sysCtx) { sysConfigBL.setValue(sysconfigName, sysconfigValue, ClientId.SYSTEM, OrgId.ANY); } }); } private String createSysConfigName(Object key) { return createSysConfigPrefix() + "." + key.toString(); } private String createSysConfigPrefix() { return SYSCONFIG_PREFIX + lookAndFeelId; } public void loadAllFromSysConfigTo(final UIDefaults uiDefaults) { if (!DB.isConnected()) { return; } final String prefix = createSysConfigPrefix() + "."; final boolean removePrefix = true; final Properties ctx = Env.getCtx(); final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx));
final Map<String, String> map = sysConfigBL.getValuesForPrefix(prefix, removePrefix, clientAndOrgId); for (final Map.Entry<String, String> mapEntry : map.entrySet()) { final String key = mapEntry.getKey(); final String valueStr = mapEntry.getValue(); try { final Object value = serializer.fromString(valueStr); uiDefaults.put(key, value); } catch (Exception ex) { logger.warn("Failed loading " + key + ": " + valueStr + ". Skipped.", ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\SysConfigUIDefaultsRepository.java
1
请完成以下Java代码
protected static void addFeature(CharSequence rawFeature, List<Integer> featureVector, FeatureMap featureMap) { int id = featureMap.idOf(rawFeature.toString()); if (id != -1) { featureVector.add(id); } } /** * 添加特征,同时清空缓存 * * @param rawFeature * @param featureVector * @param featureMap */ protected static void addFeatureThenClear(StringBuilder rawFeature, List<Integer> featureVector, FeatureMap featureMap) { int id = featureMap.idOf(rawFeature.toString()); if (id != -1) { featureVector.add(id); } rawFeature.setLength(0); } /** * 根据标注集还原字符形式的标签
* * @param tagSet * @return */ public String[] tags(TagSet tagSet) { assert tagArray != null; String[] tags = new String[tagArray.length]; for (int i = 0; i < tags.length; i++) { tags[i] = tagSet.stringOf(tagArray[i]); } return tags; } /** * 实例大小(有多少个要预测的元素) * * @return */ public int size() { return featureMatrix.length; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\instance\Instance.java
1
请完成以下Java代码
public class JavaKeyStore { private KeyStore keyStore; private String keyStoreName; private String keyStoreType; private String keyStorePassword; JavaKeyStore(String keyStoreType, String keyStorePassword, String keyStoreName) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { this.keyStoreName = keyStoreName; this.keyStoreType = keyStoreType; this.keyStorePassword = keyStorePassword; } void createEmptyKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { if(keyStoreType ==null || keyStoreType.isEmpty()){ keyStoreType = KeyStore.getDefaultType(); } keyStore = KeyStore.getInstance(keyStoreType); //load char[] pwdArray = keyStorePassword.toCharArray(); keyStore.load(null, pwdArray); // Save the keyStore FileOutputStream fos = new FileOutputStream(keyStoreName); keyStore.store(fos, pwdArray); fos.close(); } void loadKeyStore() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { char[] pwdArray = keyStorePassword.toCharArray(); FileInputStream fis = new FileInputStream(keyStoreName); keyStore.load(fis, pwdArray); fis.close(); } void setEntry(String alias, KeyStore.SecretKeyEntry secretKeyEntry, KeyStore.ProtectionParameter protectionParameter) throws KeyStoreException { keyStore.setEntry(alias, secretKeyEntry, protectionParameter); } KeyStore.Entry getEntry(String alias) throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException { KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(keyStorePassword.toCharArray()); return keyStore.getEntry(alias, protParam); } void setKeyEntry(String alias, PrivateKey privateKey, String keyPassword, Certificate[] certificateChain) throws KeyStoreException { keyStore.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), certificateChain); } void setCertificateEntry(String alias, Certificate certificate) throws KeyStoreException {
keyStore.setCertificateEntry(alias, certificate); } Certificate getCertificate(String alias) throws KeyStoreException { return keyStore.getCertificate(alias); } void deleteEntry(String alias) throws KeyStoreException { keyStore.deleteEntry(alias); } void deleteKeyStore() throws KeyStoreException, IOException { Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); keyStore.deleteEntry(alias); } keyStore = null; Path keyStoreFile = Paths.get(keyStoreName); Files.delete(keyStoreFile); } KeyStore getKeyStore() { return this.keyStore; } }
repos\tutorials-master\core-java-modules\core-java-security\src\main\java\com\baeldung\keystore\JavaKeyStore.java
1
请在Spring Boot框架中完成以下Java代码
public class MyProperties { @NotNull private InetAddress remoteAddress; @Valid private final Security security = new Security(); // @fold:on // getters/setters... public InetAddress getRemoteAddress() { return this.remoteAddress; } public void setRemoteAddress(InetAddress remoteAddress) { this.remoteAddress = remoteAddress; } public Security getSecurity() { return this.security; } // @fold:off public static class Security {
@NotEmpty private String username; // @fold:on // getters/setters... public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } // @fold:off } }
repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\features\externalconfig\typesafeconfigurationproperties\validation\nested\MyProperties.java
2
请在Spring Boot框架中完成以下Java代码
public void appReady(ApplicationReadyEvent event) throws Exception { String pathOne = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.one"; String valueOne = "one FROM:zookeeper"; String pathThree = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.three"; String valueThree = "three FROM:zookeeper"; createBaseNodes(); setValue(pathOne, valueOne); setValue(pathThree, valueThree); } private void setValue(String path, String value) throws Exception { if (client.checkExists() .forPath(path) == null) { client.create() .forPath(path, value.getBytes()); } else { client.setData() .forPath(path, value.getBytes());
} } private void createBaseNodes() throws Exception { if (client.checkExists() .forPath(CONFIG_BASE_NODE_PATH) == null) { client.create() .forPath(CONFIG_BASE_NODE_PATH); } if (client.checkExists() .forPath(APPLICATION_BASE_NODE_PATH) == null) { client.create() .forPath(APPLICATION_BASE_NODE_PATH); } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-archaius\spring-cloud-archaius-zookeeper-config\src\main\java\com\baeldung\spring\cloud\archaius\zookeeperconfig\config\ZookeeperConfigsInitializer.java
2
请完成以下Java代码
public void createFruit(@Valid Fruit fruit) { SimpleStorageService.storeFruit(fruit); } @POST @Path("/created") @Consumes(MediaType.APPLICATION_JSON) public Response createNewFruit(@Valid Fruit fruit) { String result = "Fruit saved : " + fruit; return Response.status(Response.Status.CREATED.getStatusCode()) .entity(result) .build(); } @GET @Valid
@Produces(MediaType.APPLICATION_JSON) @Path("/search/{name}") public Fruit findFruitByName(@PathParam("name") String name) { return SimpleStorageService.findByName(name); } @GET @Produces(MediaType.TEXT_HTML) @Path("/exception") @Valid public Fruit exception() { Fruit fruit = new Fruit(); fruit.setName("a"); fruit.setColour("b"); return fruit; } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\rest\FruitResource.java
1
请完成以下Java代码
private Result processInvoices(@NonNull final Iterator<InvoiceId> invoiceIds) { int counter = 0; boolean anyException = false; while (invoiceIds.hasNext()) { final InvoiceId invoiceId = invoiceIds.next(); try (final MDCCloseable invoiceCandidateIdMDC = TableRecordMDC.putTableRecordReference(I_C_Invoice.Table_Name, invoiceId)) { trxManager.runInNewTrx(() -> { logger.debug("Processing invoiceCandidate"); final I_C_Invoice invoiceRecord = invoiceDAO.getByIdInTrx(invoiceId); invoiceFacadeService.syncInvoiceToCommissionInstance(invoiceRecord); }); counter++; } catch (final RuntimeException e) {
anyException = true; final AdIssueId adIssueId = errorManager.createIssue(e); Loggables.withLogger(logger, Level.DEBUG) .addLog("C_Invoice_ID={}: Caught {} and created AD_Issue_ID={}; exception-message={}", invoiceId.getRepoId(), e.getClass(), adIssueId.getRepoId(), e.getLocalizedMessage()); } } return new Result(counter, anyException); } @Value private static class Result { int counter; boolean anyException; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\process\C_Invoice_CreateOrUpdateCommissionInstance.java
1
请完成以下Java代码
private static Optional<GeocodingConfig> toGeocodingConfig(@Nullable final I_GeocodingConfig record) { if (record == null) { return Optional.empty(); } final GeocodingProviderName providerName = GeocodingProviderName.ofNullableCode(record.getGeocodingProvider()); final GoogleMapsConfig googleMapsConfig; final OpenStreetMapsConfig openStreetMapsConfig; if (providerName == null) { return Optional.empty(); } else if (GeocodingProviderName.GOOGLE_MAPS.equals(providerName)) { googleMapsConfig = GoogleMapsConfig.builder() .apiKey(record.getgmaps_ApiKey()) .cacheCapacity(record.getcacheCapacity()) .build(); openStreetMapsConfig = null; } else if (GeocodingProviderName.OPEN_STREET_MAPS.equals(providerName)) { googleMapsConfig = null; openStreetMapsConfig = OpenStreetMapsConfig.builder() .baseURL(record.getosm_baseURL())
.millisBetweenRequests(record.getosm_millisBetweenRequests()) .cacheCapacity(record.getcacheCapacity()) .build(); } else { throw new AdempiereException("Unknown provider: " + providerName); } final GeocodingConfig geocodingConfig = GeocodingConfig.builder() .providerName(providerName) .googleMapsConfig(googleMapsConfig) .openStreetMapsConfig(openStreetMapsConfig) .build(); return Optional.of(geocodingConfig); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\GeocodingConfigRepository.java
1
请完成以下Spring Boot application配置
#chaos monkey for spring boot props management.endpoint.chaosmonkey.enabled=true management.endpoint.chaosmonkeyjmx.enabled=true spring.profiles.active=chaos-monkey #Determine whether should execute or not chaos.monkey.enabled=true #How many requests are to be attacked. 1: attack each request; 5: each 5th request is attacked chaos.monkey.assaults.level=1 #Minimum latency in ms added to the request chaos.monkey.assaults.latencyRangeStart=3000 #Maximum latency in ms added to the request chaos.monkey.assaults.latencyRangeEnd=15000 #Latency assault active chaos.monkey.assaults.latencyActive=true #Exception assault active chaos.monkey.assaults.exceptionsActive=false #AppKiller assault active chaos.monkey.assaults.killApplicationActive=false #C
ontroller watcher active chaos.monkey.watcher.controller=false #RestController watcher active chaos.monkey.watcher.restController=false #Service watcher active chaos.monkey.watcher.service=true #Repository watcher active chaos.monkey.watcher.repository=false #Component watcher active chaos.monkey.watcher.component=false
repos\tutorials-master\spring-boot-modules\spring-boot-performance\src\main\resources\application.properties
2
请完成以下Java代码
private boolean isIsRetrieveAppsActionMessage() { return retrieveAppsActionMessage; } public Builder setAccelerator(final KeyStroke accelerator) { this.accelerator = accelerator; return this; } private KeyStroke getAccelerator() { return accelerator; } public Builder setText(final String text) { this.text = text; useTextFromAction = false; return this; } public Builder useTextFromActionName() { return useTextFromActionName(true); } public Builder useTextFromActionName(final boolean useTextFromAction) { this.useTextFromAction = useTextFromAction; return this; } private final boolean isUseTextFromActionName() { return useTextFromAction; } private String getText() { return text; } public Builder setToolTipText(final String toolTipText) { this.toolTipText = toolTipText; return this; } private String getToolTipText() { return toolTipText; } /** * Advice the builder that we will build a toggle button. */ public Builder setToggleButton() { return setToggleButton(true); } /** * @param toggleButton is toggle action (maintains state) */ public Builder setToggleButton(final boolean toggleButton) { this.toggleButton = toggleButton; return this; } private boolean isToggleButton() { return toggleButton; } /** * Advice the builder to create a small size button. */ public Builder setSmallSize() { return setSmallSize(true);
} /** * Advice the builder if a small size button is needed or not. * * @param smallSize true if small size button shall be created */ public Builder setSmallSize(final boolean smallSize) { this.smallSize = smallSize; return this; } private boolean isSmallSize() { return smallSize; } /** * Advice the builder to set given {@link Insets} to action's button. * * @param buttonInsets * @see AbstractButton#setMargin(Insets) */ public Builder setButtonInsets(final Insets buttonInsets) { this.buttonInsets = buttonInsets; return this; } private final Insets getButtonInsets() { return buttonInsets; } /** * Sets the <code>defaultCapable</code> property, which determines whether the button can be made the default button for its root pane. * * @param defaultCapable * @return * @see JButton#setDefaultCapable(boolean) */ public Builder setButtonDefaultCapable(final boolean defaultCapable) { buttonDefaultCapable = defaultCapable; return this; } private Boolean getButtonDefaultCapable() { return buttonDefaultCapable; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AppsAction.java
1
请完成以下Java代码
protected static class Polygon { /** * */ protected Polyline lowerHead, lowerTail, upperHead, upperTail; } /** * */ protected static class Polyline { /** * */ protected double dx, dy;
/** * */ protected Polyline next; /** * */ protected Polyline(double dx, double dy, Polyline next) { this.dx = dx; this.dy = dy; this.next = next; } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-layout\src\main\java\org\activiti\bpmn\BPMNLayout.java
1
请完成以下Java代码
protected void subscribe(TopicSubscription subscription) { if (!subscriptions.addIfAbsent(subscription)) { String topicName = subscription.getTopicName(); throw LOG.topicNameAlreadySubscribedException(topicName); } resume(); } protected void unsubscribe(TopicSubscriptionImpl subscription) { subscriptions.remove(subscription); } public EngineClient getEngineClient() { return engineClient; } public List<TopicSubscription> getSubscriptions() { return subscriptions; } public boolean isRunning() { return isRunning.get(); } public void setBackoffStrategy(BackoffStrategy backOffStrategy) { this.backoffStrategy = backOffStrategy; } protected void runBackoffStrategy(FetchAndLockResponseDto fetchAndLockResponse) { try { List<ExternalTask> externalTasks = fetchAndLockResponse.getExternalTasks(); if (backoffStrategy instanceof ErrorAwareBackoffStrategy) { ErrorAwareBackoffStrategy errorAwareBackoffStrategy = ((ErrorAwareBackoffStrategy) backoffStrategy); ExternalTaskClientException exception = fetchAndLockResponse.getError(); errorAwareBackoffStrategy.reconfigure(externalTasks, exception); } else { backoffStrategy.reconfigure(externalTasks); } long waitTime = backoffStrategy.calculateBackoffTime(); suspend(waitTime); } catch (Throwable e) { LOG.exceptionWhileExecutingBackoffStrategyMethod(e); } } protected void suspend(long waitTime) { if (waitTime > 0 && isRunning.get()) {
ACQUISITION_MONITOR.lock(); try { if (isRunning.get()) { IS_WAITING.await(waitTime, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { LOG.exceptionWhileExecutingBackoffStrategyMethod(e); } finally { ACQUISITION_MONITOR.unlock(); } } } protected void resume() { ACQUISITION_MONITOR.lock(); try { IS_WAITING.signal(); } finally { ACQUISITION_MONITOR.unlock(); } } public void disableBackoffStrategy() { this.isBackoffStrategyDisabled.set(true); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionManager.java
1
请完成以下Java代码
public String getClientIdPrefix() { return clientIdPrefix; } public void setClientIdPrefix(String clientIdPrefix) { this.clientIdPrefix = clientIdPrefix; } @Override public Integer getConcurrency() { return concurrency; } public void setConcurrency(Integer concurrency) { this.concurrency = concurrency; } @Override public Boolean getAutoStartup() { return null; } @Override public Properties getConsumerProperties() { return consumerProperties; } public void setConsumerProperties(Properties consumerProperties) { this.consumerProperties = consumerProperties; } @Override public void setupListenerContainer(MessageListenerContainer listenerContainer, MessageConverter messageConverter) { GenericMessageListener<ConsumerRecord<K, V>> messageListener = getMessageListener(); Assert.state(messageListener != null, () -> "Endpoint [" + this + "] must provide a non null message listener"); listenerContainer.setupMessageListener(messageListener); } @Override public boolean isSplitIterables() { return splitIterables; }
public void setSplitIterables(boolean splitIterables) { this.splitIterables = splitIterables; } @Override public String getMainListenerId() { return mainListenerId; } public void setMainListenerId(String mainListenerId) { this.mainListenerId = mainListenerId; } @Override public void afterPropertiesSet() throws Exception { boolean topicsEmpty = getTopics().isEmpty(); boolean topicPartitionsEmpty = ObjectUtils.isEmpty(getTopicPartitionsToAssign()); if (!topicsEmpty && !topicPartitionsEmpty) { throw new IllegalStateException("Topics or topicPartitions must be provided but not both for " + this); } if (this.topicPattern != null && (!topicsEmpty || !topicPartitionsEmpty)) { throw new IllegalStateException("Only one of topics, topicPartitions or topicPattern must are allowed for " + this); } if (this.topicPattern == null && topicsEmpty && topicPartitionsEmpty) { throw new IllegalStateException("At least one of topics, topicPartitions or topicPattern must be provided " + "for " + this); } } @Override public String toString() { return getClass().getSimpleName() + "[" + this.id + "] topics=" + this.topics + "' | topicPattern='" + this.topicPattern + "'" + "' | topicPartitions='" + this.topicPartitions + "'" + " | messageListener='" + messageListener + "'"; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\SimpleKafkaListenerEndpoint.java
1
请完成以下Java代码
public class Carrier_ShipmentOrder_Parcel_Label_Download extends JavaProcess implements IProcessPrecondition { private final ShipmentOrderRepository orderRepository = SpringContextHolder.instance.getBean(ShipmentOrderRepository.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } if (!Objects.equals(context.getTableName(), I_Carrier_ShipmentOrder_Parcel.Table_Name)) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } final DeliveryOrderParcelId parcelId = DeliveryOrderParcelId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (parcelId == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("No parcel selected"); } final DeliveryOrderParcel parcel = orderRepository.getParcelById(parcelId); if (parcel == null || parcel.getLabelPdfBase64() == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("No label available"); } return ProcessPreconditionsResolution.accept(); }
@Override protected String doIt() { final DeliveryOrderParcelId parcelId = DeliveryOrderParcelId.ofRepoIdOrNull(getRecord_ID()); if (parcelId == null) { return MSG_OK; } final DeliveryOrderParcel parcel = orderRepository.getParcelById(parcelId); if (parcel == null || parcel.getLabelPdfBase64() == null) { return MSG_OK; } getResult().setReportData(new ByteArrayResource(parcel.getLabelPdfBase64()), "Awb_" + parcel.getAwb(), MimeType.TYPE_PDF); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\process\Carrier_ShipmentOrder_Parcel_Label_Download.java
1
请在Spring Boot框架中完成以下Java代码
public Compression getCompression() { return this.compression; } public void setCompression(Compression compression) { this.compression = compression; } public Map<String, String> getHeaders() { return this.headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; }
public enum Compression { /** * Gzip compression. */ GZIP, /** * No compression. */ NONE } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\otlp\OtlpTracingProperties.java
2
请完成以下Java代码
public class C_SubscriptionProgress_ChangeRecipient extends C_SubscriptionProgressBase { @Param(parameterName = "DateGeneral", mandatory = false) private Timestamp dateFrom; @Param(parameterName = "DateGeneral", mandatory = false, parameterTo = true) private Timestamp dateTo; @Param(parameterName = "DropShip_BPartner_ID", mandatory = true) private int DropShip_BPartner_ID; @Param(parameterName = "DropShip_Location_ID", mandatory = true) private int DropShip_Location_ID; @Param(parameterName = "DropShip_User_ID", mandatory = false) private int DropShip_User_ID; @Param(parameterName = "IsPermanentRecipient", mandatory = true) private boolean isPermanentRecipient; @Override
protected String doIt() { final ChangeRecipientsRequest request = ChangeRecipientsRequest.builder() .term(getTermFromProcessInfo()) .dateFrom(dateFrom) .dateTo(dateTo) .DropShip_BPartner_ID(DropShip_BPartner_ID) .DropShip_Location_ID(DropShip_Location_ID) .DropShip_User_ID(DropShip_User_ID) .IsPermanentRecipient(isPermanentRecipient) .build(); SubscriptionService.changeRecipient(request); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\process\C_SubscriptionProgress_ChangeRecipient.java
1
请在Spring Boot框架中完成以下Java代码
public AllocationAmounts convertToRealAmounts(@NonNull final InvoiceAmtMultiplier invoiceAmtMultiplier) { return negateIf(invoiceAmtMultiplier.isNegateToConvertToRealValue()); } private AllocationAmounts negateIf(final boolean condition) { return condition ? negate() : this; } public AllocationAmounts negate() { if (isZero()) { return this; } return toBuilder() .payAmt(this.payAmt.negate()) .discountAmt(this.discountAmt.negate()) .writeOffAmt(this.writeOffAmt.negate()) .invoiceProcessingFee(this.invoiceProcessingFee) // never negate the processing fee because it will be paid to the service provider no matter what kind of invoice it is applied to. .build(); } public Money getTotalAmt() {
return payAmt.add(discountAmt).add(writeOffAmt).add(invoiceProcessingFee); } public boolean isZero() { return payAmt.signum() == 0 && discountAmt.signum() == 0 && writeOffAmt.signum() == 0 && invoiceProcessingFee.signum() == 0; } public AllocationAmounts toZero() { return isZero() ? this : AllocationAmounts.zero(getCurrencyId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\AllocationAmounts.java
2
请完成以下Java代码
public Tutorials getFullDocument() { try { JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile()); return tutorials; } catch (JAXBException e) { e.printStackTrace(); return null; } } public void createNewDocument() { Tutorials tutorials = new Tutorials(); tutorials.setTutorial(new ArrayList<Tutorial>()); Tutorial tut = new Tutorial(); tut.setTutId("01"); tut.setType("XML"); tut.setTitle("XML with Jaxb"); tut.setDescription("XML Binding with Jaxb"); tut.setDate("04/02/2015"); tut.setAuthor("Jaxb author"); tutorials.getTutorial().add(tut); try { JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(tutorials, file);
} catch (JAXBException e) { e.printStackTrace(); } } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\JaxbParser.java
1
请在Spring Boot框架中完成以下Java代码
public class UserDataPublisher implements Publisher<UserData>, Subscription { private static final Logger LOG = LoggerFactory.getLogger(UserDataPublisher.class); private final List<UserData> users; private Subscriber<? super UserData> subscriber; private long start; private PublishTask publishTask; public UserDataPublisher(List<UserData> users) { this.users = users; } @Override public void subscribe(Subscriber<? super UserData> subscriber) { LOG.info("subscribe"); this.subscriber = subscriber; this.start = 0; this.subscriber.onSubscribe(this); }
@Override public synchronized void request(long n) { long startIndex = start; LOG.info("request n={} start={}", n, startIndex); start = start + n; publishTask = new PublishTask(users, startIndex, n, subscriber); publishTask.publish(); } @Override public void cancel() { LOG.info("cancel"); if (publishTask != null) { publishTask.setStopped(); } } }
repos\spring-examples-java-17\spring-webflux\src\main\java\itx\examples\webflux\services\UserDataPublisher.java
2
请完成以下Java代码
private void extractBeneficiaryToInvoice( @NonNull final XmlRequest xRequest, @NonNull final I_C_Invoice invoiceRecord, @NonNull final AttachmentEntry attachmentEntry /*needed for logging*/) { final XmlPatient patient = xRequest.getPayload().getBody().getTiers().getPatient(); final XmlBiller biller = xRequest.getPayload().getBody().getTiers().getBiller(); final ExternalId externalId = HealthcareCHHelper.createBPartnerExternalIdForPatient(biller.getEanParty(), patient.getSsn()); if (externalId == null) { logger.debug("patient-XML data extracted from attachmentEntry with id={} (filename={}) has no patient-SSN or biller-EAN; -> doing nothing", attachmentEntry.getId(), attachmentEntry.getFilename()); return; } final BPartnerQuery bPartnerQuery = BPartnerQuery.builder().externalId(externalId) .onlyOrgId(OrgId.ANY) .onlyOrgId(OrgId.ofRepoId(invoiceRecord.getAD_Org_ID())) // make sure that we don't run into "stale" customers from other orgs that happen to have the same orgId. .build(); final ImmutableList<BPartnerComposite> bpartners = bpartnerCompositeRepository.getByQuery(bPartnerQuery); if (bpartners.isEmpty()) { logger.debug("externalId={} of the patient-XML data extracted from attachmentEntry with id={} (filename={}) has no matching C_BPartner; -> doing nothing", externalId.getValue(), attachmentEntry.getId(), attachmentEntry.getFilename()); return; } final BPartnerComposite bPartner = CollectionUtils.singleElement(bpartners); if (invoiceRecord.getBeneficiary_BPartner_ID() > 0) { logger.debug("C_Invoice with ID={} already has a Beneficiary_BPartner_ID > 0; -> doing nothing", invoiceRecord.getC_Invoice_ID()); return; }
final int beneficiaryRepoId = bPartner.getBpartner().getId().getRepoId(); invoiceRecord.setBeneficiary_BPartner_ID(beneficiaryRepoId); logger.debug("set Beneficiary_BPartner_ID={} from the patient-XML data's SSN={} extracted from attachmentEntry with id={} (filename={})", beneficiaryRepoId, patient.getSsn(), attachmentEntry.getId(), attachmentEntry.getFilename()); final BPartnerLocation location = bPartner .extractShipToLocation() .orElseGet(() -> bPartner.extractBillToLocation().orElse(null)); if (location != null) { invoiceRecord.setBeneficiary_Location_ID(location.getId().getRepoId()); logger.debug("set setBeneficiary_Location_ID={} from the patient-XML data's SSN={} extracted from attachmentEntry with id={} (filename={})", location.getId().getRepoId(), patient.getSsn(), attachmentEntry.getId(), attachmentEntry.getFilename()); } saveRecord(invoiceRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\export\HealthcareXMLAttachedToInvoiceListener.java
1
请完成以下Java代码
public LogicExpressionResult getAllowDeleteDocument() { return allowDelete; } public void assertDeleteDocumentAllowed(final IncludedDocumentsCollectionActionsContext context) { final LogicExpressionResult allowDelete = updateAndGetAllowDeleteDocument(context); if (allowDelete.isFalse()) { throw new InvalidDocumentStateException(parentDocumentPath, "Cannot delete included document because it's not allowed: " + allowDelete); } } public LogicExpressionResult updateAndGetAllowDeleteDocument(final IncludedDocumentsCollectionActionsContext context) { final LogicExpressionResult allowDeleteOld = allowDelete; final LogicExpressionResult allowDelete = computeAllowDeleteDocument(context); this.allowDelete = allowDelete; if (!allowDeleteOld.equalsByNameAndValue(allowDelete)) { context.collectAllowDelete(parentDocumentPath, detailId, allowDelete); } return allowDelete; } private LogicExpressionResult computeAllowDeleteDocument(final IncludedDocumentsCollectionActionsContext context) { // Quickly check if the allowDelete logic it's constant and it's false. // In that case we can return right away. if (allowDeleteLogic.isConstantFalse()) { return LogicExpressionResult.ofConstantExpression(allowDeleteLogic);
} if (context.isParentDocumentProcessed()) { return DISALLOW_ParentDocumentProcessed; } if (!context.isParentDocumentActive()) { return DISALLOW_ParentDocumentNotActive; } final LogicExpressionResult allowDelete = allowDeleteLogic.evaluateToResult(context.toEvaluatee(), OnVariableNotFound.ReturnNoResult); return allowDelete; } public void onNewDocument(final Document document, final IncludedDocumentsCollectionActionsContext context) { if (document.isNew()) { setAllowNewAndCollect(DISALLOW_AnotherNewDocumentAlreadyExists, context); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\IncludedDocumentsCollectionActions.java
1
请完成以下Java代码
public Collection<String> getHeaderNames() { return this.headers.keySet(); } @Override public List<Locale> getLocales() { return this.locales; } @Override public String[] getParameterValues(String name) { return this.parameters.getOrDefault(name, new String[0]); } @Override public Map<String, String[]> getParameterMap() { return this.parameters; } public void setRedirectUrl(String redirectUrl) { Assert.notNull(redirectUrl, "redirectUrl cannot be null"); this.redirectUrl = redirectUrl; } public void setCookies(List<Cookie> cookies) { Assert.notNull(cookies, "cookies cannot be null"); this.cookies = cookies; } public void setMethod(String method) {
Assert.notNull(method, "method cannot be null"); this.method = method; } public void setHeaders(Map<String, List<String>> headers) { Assert.notNull(headers, "headers cannot be null"); this.headers = headers; } public void setLocales(List<Locale> locales) { Assert.notNull(locales, "locales cannot be null"); this.locales = locales; } public void setParameters(Map<String, String[]> parameters) { Assert.notNull(parameters, "parameters cannot be null"); this.parameters = parameters; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\SimpleSavedRequest.java
1
请完成以下Java代码
public void setActionListener(final FindPanelActionListener actionListener) { Check.assumeNotNull(actionListener, "actionListener not null"); this.actionListener = actionListener; } private void setDefaultButton() { setDefaultButton(confirmPanel.getOKButton()); } private void setDefaultButton(final JButton button) { final Window frame = AEnv.getWindow(this); if (frame instanceof RootPaneContainer) { final RootPaneContainer c = (RootPaneContainer)frame; c.getRootPane().setDefaultButton(button); } } /** * Get Icon with name action * * @param name name * @param small small * @return Icon */ private final ImageIcon getIcon(String name) { final String fullName = name + (drawSmallButtons ? "16" : "24"); return Images.getImageIcon2(fullName); } /** * @return true if the panel is visible and it has at least one field in simple search mode */ @Override public boolean isFocusable() { if (!isVisible()) { return false; } if (isSimpleSearchPanelActive()) { return m_editorFirst != null; } return false; } @Override public void setFocusable(final boolean focusable) { // ignore it } @Override public void requestFocus() { if (isSimpleSearchPanelActive()) {
if (m_editorFirst != null) { m_editorFirst.requestFocus(); } } } @Override public boolean requestFocusInWindow() { if (isSimpleSearchPanelActive()) { if (m_editorFirst != null) { return m_editorFirst.requestFocusInWindow(); } } return false; } private boolean disposed = false; boolean isDisposed() { return disposed; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanel.java
1
请完成以下Java代码
public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getCauseIncidentId() { return causeIncidentId; } public void setCauseIncidentId(String causeIncidentId) { this.causeIncidentId = causeIncidentId; } public String getRootCauseIncidentId() { return rootCauseIncidentId; } public void setRootCauseIncidentId(String rootCauseIncidentId) { this.rootCauseIncidentId = rootCauseIncidentId; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public String getHistoryConfiguration() { return historyConfiguration; } public void setHistoryConfiguration(String historyConfiguration) { this.historyConfiguration = historyConfiguration; } public String getIncidentMessage() { return incidentMessage; } public void setIncidentMessage(String incidentMessage) { this.incidentMessage = incidentMessage; } public void setIncidentState(int incidentState) { this.incidentState = incidentState; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getJobDefinitionId() { return jobDefinitionId; }
public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public boolean isOpen() { return IncidentState.DEFAULT.getStateCode() == incidentState; } public boolean isDeleted() { return IncidentState.DELETED.getStateCode() == incidentState; } public boolean isResolved() { return IncidentState.RESOLVED.getStateCode() == incidentState; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIncidentEventEntity.java
1
请完成以下Java代码
public class ProcessDocuments extends AbstractProcessDocumentsTemplate { // services private final IQueryBL queryBL = Services.get(IQueryBL.class); private final IADTableDAO adTableDAO = Services.get(IADTableDAO.class); public static final String PARAM_AD_Table_ID = "AD_Table_ID"; @Param(parameterName = PARAM_AD_Table_ID, mandatory = true) private int p_AD_Table_ID = -1; public static final String PARAM_DocStatus = "DocStatus"; @Param(parameterName = PARAM_DocStatus) private DocStatus p_DocStatus; public static final String PARAM_WhereClause = "WhereClause"; @Param(parameterName = PARAM_WhereClause) private String p_WhereClause; public static final String PARAM_DocAction = "DocAction"; @Param(parameterName = PARAM_DocAction) private String p_DocAction; @Override protected Iterator<GenericPO> retrieveDocumentsToProcess() { if (p_AD_Table_ID <= 0) {
throw new FillMandatoryException(PARAM_AD_Table_ID); } final String tableName = adTableDAO.retrieveTableName(this.p_AD_Table_ID); final IQueryBuilder<Object> queryBuilder = queryBL.createQueryBuilder(tableName) .addOnlyActiveRecordsFilter(); if (p_DocStatus != null) { queryBuilder.addEqualsFilter(PARAM_DocStatus, p_DocStatus); } if (!Check.isBlank(p_WhereClause)) { queryBuilder.filter(TypedSqlQueryFilter.of(p_WhereClause)); } return queryBuilder.create().iterate(GenericPO.class); } @Override protected String getDocAction() {return p_DocAction;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\process\ProcessDocuments.java
1
请完成以下Java代码
public class ObjectMapperBuilder { private boolean enableIndentation; private boolean preserveOrder; private DateFormat dateFormat; public ObjectMapperBuilder enableIndentation() { this.enableIndentation = true; return this; } public ObjectMapperBuilder dateFormat() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm a z", Locale.ENGLISH); simpleDateFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("Asia/Kolkata"))); this.dateFormat = simpleDateFormat; return this; }
public ObjectMapperBuilder preserveOrder(boolean order) { this.preserveOrder = order; return this; } public ObjectMapper build() { ObjectMapper objectMapper = JsonMapper.builder() .configure(SerializationFeature.INDENT_OUTPUT, this.enableIndentation) .defaultDateFormat(this.dateFormat) .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, this.preserveOrder) .build(); return objectMapper; } }
repos\tutorials-master\jackson-simple\src\main\java\com\baeldung\jackson\objectmapper\ObjectMapperBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class C_Project_CreateQuotation extends ServiceOrRepairProjectBasedProcess implements IProcessPrecondition { @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { final ProjectId projectId = ProjectId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (projectId == null) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } return checkIsServiceOrRepairProject(projectId); } @Override protected String doIt() { final ProjectId projectId = getProjectId(); checkIsServiceOrRepairProject(projectId).throwExceptionIfRejected(); final OrderId quotationId = projectService.createQuotationFromProject(CreateQuotationFromProjectRequest.builder() .projectId(projectId)
.build()); setRecordToOpen(quotationId); return MSG_OK; } private void setRecordToOpen(final OrderId quotationId) { getResult().setRecordToOpen(ProcessExecutionResult.RecordsToOpen.builder() .record(TableRecordReference.of(I_C_Order.Table_Name, quotationId)) .target(ProcessExecutionResult.RecordsToOpen.OpenTarget.SingleDocument) .targetTab(ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\C_Project_CreateQuotation.java
2
请完成以下Java代码
boolean isNoCacheRequestWithoutUpdate(ServerHttpRequest request) { return LocalResponseCacheUtils.isNoCacheRequest(request) && ignoreNoCacheUpdate; } private boolean isStatusCodeToCache(ServerHttpResponse response) { return statusesToCache.contains(response.getStatusCode()); } boolean isRequestCacheable(ServerHttpRequest request) { return HttpMethod.GET.equals(request.getMethod()) && !hasRequestBody(request) && isCacheControlAllowed(request); } private boolean isVaryWildcard(ServerHttpResponse response) { HttpHeaders headers = response.getHeaders(); List<String> varyValues = headers.getOrEmpty(HttpHeaders.VARY); return varyValues.stream().anyMatch(VARY_WILDCARD::equals); } private boolean isCacheControlAllowed(HttpMessage request) { HttpHeaders headers = request.getHeaders(); List<String> cacheControlHeader = headers.getOrEmpty(HttpHeaders.CACHE_CONTROL); return cacheControlHeader.stream().noneMatch(forbiddenCacheControlValues::contains); } private static boolean hasRequestBody(ServerHttpRequest request) { return request.getHeaders().getContentLength() > 0; } private void saveInCache(String cacheKey, CachedResponse cachedResponse) { try { cache.put(cacheKey, cachedResponse);
} catch (RuntimeException anyException) { LOGGER.error("Error writing into cache. Data will not be cached", anyException); } } private void saveMetadataInCache(String metadataKey, CachedResponseMetadata metadata) { try { cache.put(metadataKey, metadata); } catch (RuntimeException anyException) { LOGGER.error("Error writing into cache. Data will not be cached", anyException); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\ResponseCacheManager.java
1
请完成以下Java代码
public boolean equals(GraphicInfo ginfo) { if (this.getX() != ginfo.getX()) { return false; } if (this.getY() != ginfo.getY()) { return false; } if (this.getHeight() != ginfo.getHeight()) { return false; } if (this.getWidth() != ginfo.getWidth()) { return false; } if (this.getRotation() != ginfo.getRotation()) { return false; }
// check for zero value in case we are comparing model value to BPMN DI value // model values do not have xml location information if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) { return false; } if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) { return false; } // only check for elements that support this value if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) { return false; } return true; } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\GraphicInfo.java
1
请在Spring Boot框架中完成以下Java代码
public JdbcTokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.passwordEncoder(passwordEncoder); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(auth) .tokenStore(tokenStore()) ; } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource) .passwordEncoder(passwordEncoder) .withClient("client") .secret("secret") .authorizedGrantTypes("password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(3600) // 1 hour .refreshTokenValiditySeconds(2592000) // 30 days .and() .withClient("svca-service") .secret("password") .authorizedGrantTypes("client_credentials", "refresh_token") .scopes("server") .and() .withClient("svcb-service") .secret("password") .authorizedGrantTypes("client_credentials", "refresh_token") .scopes("server")
; } @Configuration @Order(-20) protected static class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter { @Autowired private DataSource dataSource; @Override public void init(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().dataSource(dataSource) .withUser("dave").password("secret").roles("USER") .and() .withUser("anil").password("password").roles("ADMIN") ; } } }
repos\spring-boot-cloud-master\auth-service\src\main\java\cn\zhangxd\auth\config\OAuthConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
private boolean isTemplateAvailable(String view, ResourceLoader resourceLoader, TemplateAvailabilityProperties properties) { String location = properties.getPrefix() + view + properties.getSuffix(); for (String path : properties.getLoaderPath()) { if (resourceLoader.getResource(path + location).exists()) { return true; } } return false; } protected abstract static class TemplateAvailabilityProperties { private String prefix; private String suffix; protected TemplateAvailabilityProperties(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } protected abstract List<String> getLoaderPath();
public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\template\PathBasedTemplateAvailabilityProvider.java
2
请完成以下Java代码
/* package */final class DocumentNoInfo implements IDocumentNoInfo { public static final Builder builder() { return new Builder(); } private final String docBaseType; private final String docSubType; private final boolean soTrx; private final boolean hasChanges; private final boolean docNoControlled; private final String documentNo; private DocumentNoInfo(final Builder builder) { super(); this.documentNo = builder.documentNo; this.docBaseType = builder.docBaseType; this.docSubType = builder.docSubType; this.soTrx = builder.soTrx; this.hasChanges = builder.hasChanges; this.docNoControlled = builder.docNoControlled; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("documentNo", documentNo) .add("docBaseType", docBaseType) .add("docSubType", docSubType) .add("IsSOTrx", soTrx) .add("hasChanges", hasChanges) .add("docNoControlled", docNoControlled) .toString(); } @Override public String getDocBaseType() { return docBaseType; } @Override public String getDocSubType() { return docSubType; } @Override public boolean isSOTrx() { return soTrx; } @Override public boolean isHasChanges() { return hasChanges; } @Override public boolean isDocNoControlled() { return docNoControlled;
} @Override public String getDocumentNo() { return documentNo; } public static final class Builder { private String docBaseType; private String docSubType; private boolean soTrx; private boolean hasChanges; private boolean docNoControlled; private String documentNo; private Builder() { super(); } public DocumentNoInfo build() { return new DocumentNoInfo(this); } public Builder setDocumentNo(final String documentNo) { this.documentNo = documentNo; return this; } public Builder setDocBaseType(final String docBaseType) { this.docBaseType = docBaseType; return this; } public Builder setDocSubType(final String docSubType) { this.docSubType = docSubType; return this; } public Builder setHasChanges(final boolean hasChanges) { this.hasChanges = hasChanges; return this; } public Builder setDocNoControlled(final boolean docNoControlled) { this.docNoControlled = docNoControlled; return this; } public Builder setIsSOTrx(final boolean isSOTrx) { soTrx = isSOTrx; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoInfo.java
1
请完成以下Java代码
public DocumentFilter createOrderLineDocumentFilter(@NonNull final OrderLineId orderLineId) { final OrderLine salesOrderLine = orderLineRepository.getById(orderLineId); return createOrderLineDocumentFilter(salesOrderLine); } private DocumentFilter createOrderLineDocumentFilter(@NonNull final OrderLine salesOrderLine) { final IHUQueryBuilder huQuery = createHUQuery(salesOrderLine); return HUIdsFilterHelper.createFilter(huQuery); } private IHUQueryBuilder createHUQuery(@NonNull final OrderLine salesOrderLine) { final OrderLineId salesOrderLineId = salesOrderLine.getId(); final HUReservationDocRef reservationDocRef = salesOrderLineId != null ? HUReservationDocRef.ofSalesOrderLineId(salesOrderLineId) : null; return huReservationService.prepareHUQuery() .warehouseId(salesOrderLine.getWarehouseId()) .productId(salesOrderLine.getProductId()) .bpartnerId(salesOrderLine.getBPartnerId()) .asiId(salesOrderLine.getAsiId()) .reservedToDocumentOrNotReservedAtAll(reservationDocRef) .build(); } public DocumentFilter createDocumentFilterIgnoreAttributes(@NonNull final Packageable packageable) { final IHUQueryBuilder huQuery = createHUQueryIgnoreAttributes(packageable);
return HUIdsFilterHelper.createFilter(huQuery); } private IHUQueryBuilder createHUQueryIgnoreAttributes(final Packageable packageable) { final OrderLineId salesOrderLineId = packageable.getSalesOrderLineIdOrNull(); final HUReservationDocRef reservationDocRef = salesOrderLineId != null ? HUReservationDocRef.ofSalesOrderLineId(salesOrderLineId) : null; return huReservationService.prepareHUQuery() .warehouseId(packageable.getWarehouseId()) .productId(packageable.getProductId()) .bpartnerId(packageable.getCustomerId()) .asiId(null) // ignore attributes .reservedToDocumentOrNotReservedAtAll(reservationDocRef) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\hu\reservation\HUReservationDocumentFilterService.java
1
请完成以下Java代码
public Stream<HUEditorRow> streamByIds(final DocumentIdsSelection rowIds) { if (rowIds.isEmpty()) { return Stream.empty(); } return streamByIds(HUEditorRowFilter.onlyRowIds(rowIds)); } public Stream<HUEditorRow> streamByIds(final HUEditorRowFilter filter) { return rowsBuffer.streamByIdsExcludingIncludedRows(filter); } /** * @return top level rows and included rows recursive stream which are matching the given filter */ public Stream<HUEditorRow> streamAllRecursive(final HUEditorRowFilter filter) { return rowsBuffer.streamAllRecursive(filter); } /** * @return true if there is any top level or included row which is matching given filter */ public boolean matchesAnyRowRecursive(final HUEditorRowFilter filter) { return rowsBuffer.matchesAnyRowRecursive(filter); } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { final Set<HuId> huIds = streamByIds(rowIds) .filter(HUEditorRow::isPureHU) .map(HUEditorRow::getHuId)
.filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); if (huIds.isEmpty()) { return ImmutableList.of(); } final List<I_M_HU> hus = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class) .addInArrayFilter(I_M_HU.COLUMN_M_HU_ID, huIds) .create() .list(I_M_HU.class); return InterfaceWrapperHelper.createList(hus, modelClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorView.java
1
请完成以下Java代码
public void reset() { this.stripPaths = false; } /** * Ensures {@link FirewalledRequest#reset()} is called prior to performing a forward. * It then delegates work to the {@link RequestDispatcher} from the original * {@link HttpServletRequest}. * * @author Rob Winch */ private class FirewalledRequestAwareRequestDispatcher implements RequestDispatcher { private final String path; /** * @param path the {@code path} that will be used to obtain the delegate * {@link RequestDispatcher} from the original {@link HttpServletRequest}. */ FirewalledRequestAwareRequestDispatcher(String path) { this.path = path; }
@Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { reset(); getDelegateDispatcher().forward(request, response); } @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { getDelegateDispatcher().include(request, response); } private RequestDispatcher getDelegateDispatcher() { return RequestWrapper.super.getRequestDispatcher(this.path); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\RequestWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getIncludeCaseVariables() { return includeCaseVariables; } public void setIncludeCaseVariables(Boolean includeCaseVariables) { this.includeCaseVariables = includeCaseVariables; } public Collection<String> getIncludeCaseVariablesNames() { return includeCaseVariablesNames; } public void setIncludeCaseVariablesNames(Collection<String> includeCaseVariablesNames) { this.includeCaseVariablesNames = includeCaseVariablesNames; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public List<QueryVariable> getVariables() { return variables; } public void setVariables(List<QueryVariable> variables) { this.variables = variables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) { this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId;
} public Boolean getWithoutCaseInstanceParentId() { return withoutCaseInstanceParentId; } public void setWithoutCaseInstanceParentId(Boolean withoutCaseInstanceParentId) { this.withoutCaseInstanceParentId = withoutCaseInstanceParentId; } public Boolean getWithoutCaseInstanceCallbackId() { return withoutCaseInstanceCallbackId; } public void setWithoutCaseInstanceCallbackId(Boolean withoutCaseInstanceCallbackId) { this.withoutCaseInstanceCallbackId = withoutCaseInstanceCallbackId; } public Set<String> getCaseInstanceCallbackIds() { return caseInstanceCallbackIds; } public void setCaseInstanceCallbackIds(Set<String> caseInstanceCallbackIds) { this.caseInstanceCallbackIds = caseInstanceCallbackIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceQueryRequest.java
2
请完成以下Java代码
public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Bar [name=").append(name).append("]"); return builder.toString(); } @PrePersist public void onPrePersist() { logger.info("@PrePersist"); audit(OPERATION.INSERT); } @PreUpdate public void onPreUpdate() { logger.info("@PreUpdate"); audit(OPERATION.UPDATE); } @PreRemove public void onPreRemove() { logger.info("@PreRemove"); audit(OPERATION.DELETE); } private void audit(final OPERATION operation) { setOperation(operation); setTimestamp((new Date()).getTime()); } public enum OPERATION {
INSERT, UPDATE, DELETE; private String value; OPERATION() { value = toString(); } public static OPERATION parse(final String value) { OPERATION operation = null; for (final OPERATION op : OPERATION.values()) { if (op.getValue().equals(value)) { operation = op; break; } } return operation; } public String getValue() { return value; } } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Bar.java
1
请完成以下Java代码
private ImportInvoiceResponseRequest createRequest(@NonNull final Path fileToImport) { try { final byte[] fileContent = Files.readAllBytes(fileToImport); final String fileName = fileToImport.getFileName().toString(); return ImportInvoiceResponseRequest .builder() .data(fileContent) .fileName(fileName) .mimeType(MimeType.getMimeType(fileName)) .build(); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e);
} } private void moveFile(@NonNull final Path fileToMove, @NonNull final Path outputDirectory) { try { Files.move(fileToMove, outputDirectory.resolve(fileToMove.getFileName())); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\imp\process\C_Invoice_ImportInvoiceResponse.java
1
请完成以下Java代码
public AdMessagesTree load(@NonNull final String adLanguage) {return build().load(adLanguage);} } public AdMessagesTree load(@NonNull final String adLanguage) { final LinkedHashMap<String, Object> tree = new LinkedHashMap<>(); //tree.put("_language", adLanguage); loadInto(tree, adLanguage, adMessageKey -> adMessageKey); return AdMessagesTree.builder() .adLanguage(adLanguage) .map(tree) .build(); } private void loadInto( @NonNull Map<String, Object> tree, @NonNull final String adLanguage, @NonNull final UnaryOperator<String> keyMapper) { msgBL.getMsgMap(adLanguage, adMessagePrefix, true /* removePrefix */) .forEach((adMessageKey, msgText) -> { if (filterAdMessagesBy == null || filterAdMessagesBy.test(adMessageKey)) { addMessageToTree(tree, keyMapper.apply(adMessageKey), msgText); } }); } private static void addMessageToTree(final Map<String, Object> tree, final String key, final String value) { final List<String> keyParts = SPLIT_BY_DOT.splitToList(key); Map<String, Object> currentNode = tree; for (int i = 0; i < keyParts.size() - 1; i++) { final String keyPart = keyParts.get(i); final Object currentNodeObj = currentNode.get(keyPart); if (currentNodeObj == null) {
final Map<String, Object> parentNode = currentNode; currentNode = new LinkedHashMap<>(); parentNode.put(keyPart, currentNode); } else if (currentNodeObj instanceof Map) { //noinspection unchecked currentNode = (Map<String, Object>)currentNodeObj; } else { // discarding the old value, shall not happen final Map<String, Object> parentNode = currentNode; currentNode = new LinkedHashMap<>(); parentNode.put(keyPart, currentNode); } } final String keyPart = keyParts.get(keyParts.size() - 1); currentNode.put(keyPart, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\AdMessagesTreeLoader.java
1
请在Spring Boot框架中完成以下Java代码
public class Saml2ResponseAssertion implements Saml2ResponseAssertionAccessor { @Serial private static final long serialVersionUID = -7505233045395024212L; private final String responseValue; private final String nameId; private final List<String> sessionIndexes; private final Map<String, List<Object>> attributes; Saml2ResponseAssertion(String responseValue, String nameId, List<String> sessionIndexes, Map<String, List<Object>> attributes) { Assert.notNull(responseValue, "response value cannot be null"); Assert.notNull(nameId, "nameId cannot be null"); Assert.notNull(sessionIndexes, "sessionIndexes cannot be null"); Assert.notNull(attributes, "attributes cannot be null"); this.responseValue = responseValue; this.nameId = nameId; this.sessionIndexes = sessionIndexes; this.attributes = attributes; } public static Builder withResponseValue(String responseValue) { return new Builder(responseValue); } @Override public String getNameId() { return this.nameId; } @Override public List<String> getSessionIndexes() { return this.sessionIndexes; } @Override public Map<String, List<Object>> getAttributes() { return this.attributes; } @Override public String getResponseValue() { return this.responseValue; } public static final class Builder { private final String responseValue; private String nameId; private List<String> sessionIndexes = List.of(); private Map<String, List<Object>> attributes = Map.of();
Builder(String responseValue) { this.responseValue = responseValue; } public Builder nameId(String nameId) { this.nameId = nameId; return this; } public Builder sessionIndexes(List<String> sessionIndexes) { this.sessionIndexes = sessionIndexes; return this; } public Builder attributes(Map<String, List<Object>> attributes) { this.attributes = attributes; return this; } public Saml2ResponseAssertion build() { return new Saml2ResponseAssertion(this.responseValue, this.nameId, this.sessionIndexes, this.attributes); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2ResponseAssertion.java
2
请完成以下Java代码
public void print(char c) throws IOException { trackContentLength(c); this.delegate.print(c); } @Override public void print(double d) throws IOException { trackContentLength(d); this.delegate.print(d); } @Override public void print(float f) throws IOException { trackContentLength(f); this.delegate.print(f); } @Override public void print(int i) throws IOException { trackContentLength(i); this.delegate.print(i); } @Override public void print(long l) throws IOException { trackContentLength(l); this.delegate.print(l); } @Override public void print(String s) throws IOException { trackContentLength(s); this.delegate.print(s); } @Override public void println() throws IOException { trackContentLengthLn(); this.delegate.println(); } @Override public void println(boolean b) throws IOException { trackContentLength(b); trackContentLengthLn(); this.delegate.println(b); } @Override public void println(char c) throws IOException { trackContentLength(c); trackContentLengthLn(); this.delegate.println(c); } @Override public void println(double d) throws IOException { trackContentLength(d); trackContentLengthLn(); this.delegate.println(d); } @Override public void println(float f) throws IOException { trackContentLength(f); trackContentLengthLn(); this.delegate.println(f); } @Override public void println(int i) throws IOException { trackContentLength(i); trackContentLengthLn(); this.delegate.println(i); } @Override public void println(long l) throws IOException { trackContentLength(l);
trackContentLengthLn(); this.delegate.println(l); } @Override public void println(String s) throws IOException { trackContentLength(s); trackContentLengthLn(); this.delegate.println(s); } @Override public void write(byte[] b) throws IOException { trackContentLength(b); this.delegate.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { checkContentLength(len); this.delegate.write(b, off, len); } @Override public boolean isReady() { return this.delegate.isReady(); } @Override public void setWriteListener(WriteListener writeListener) { this.delegate.setWriteListener(writeListener); } @Override public boolean equals(Object obj) { return this.delegate.equals(obj); } @Override public int hashCode() { return this.delegate.hashCode(); } @Override public String toString() { return getClass().getName() + "[delegate=" + this.delegate.toString() + "]"; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\OnCommittedResponseWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public int getConnectionMinimumIdleSize() { return connectionMinimumIdleSize; } public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) { this.connectionMinimumIdleSize = connectionMinimumIdleSize; } public int getConnectionPoolSize() { return connectionPoolSize; } public void setConnectionPoolSize(int connectionPoolSize) { this.connectionPoolSize = connectionPoolSize; } public int getDatabase() { return database; } public void setDatabase(int database) { this.database = database; } public boolean isDnsMonitoring() { return dnsMonitoring; } public void setDnsMonitoring(boolean dnsMonitoring) { this.dnsMonitoring = dnsMonitoring;
} public int getDnsMonitoringInterval() { return dnsMonitoringInterval; } public void setDnsMonitoringInterval(int dnsMonitoringInterval) { this.dnsMonitoringInterval = dnsMonitoringInterval; } public String getCodec() { return codec; } public void setCodec(String codec) { this.codec = codec; } }
repos\kkFileView-master\server\src\main\java\cn\keking\config\RedissonConfig.java
2
请完成以下Java代码
public boolean hasEditableRow() { return editableRowId != null; } public DocumentId getEditableRowId() { if (editableRowId == null) { throw new AdempiereException("No editable row found"); } return editableRowId; } public PricingConditionsRow getEditableRow() { return getById(getEditableRowId()); } public DocumentFilterList getFilters()
{ return filters; } public PricingConditionsRowData filter(@NonNull final DocumentFilterList filters) { if (DocumentFilterList.equals(this.filters, filters)) { return this; } if (filters.isEmpty()) { return getAllRowsData(); } return new PricingConditionsRowData(this, filters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowData.java
1
请在Spring Boot框架中完成以下Java代码
public String detail(HttpServletRequest request, @PathVariable("newsId") Long newsId) { News newsDetail = newsService.queryNewsById(newsId); if (newsDetail != null) { request.setAttribute("newsDetail", newsDetail); request.setAttribute("pageName", "详情"); return "index/detail"; } else { return "error/error_404"; } } /** * 评论操作 */ @PostMapping(value = "/news/comment") @ResponseBody public Result comment(HttpServletRequest request, HttpSession session, @RequestParam Long newsId, @RequestParam String verifyCode, @RequestParam String commentator, @RequestParam String commentBody) { if (!StringUtils.hasText(verifyCode)) { return ResultGenerator.genFailResult("验证码不能为空"); } ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute("verifyCode"); if (shearCaptcha == null || !shearCaptcha.verify(verifyCode)) { return ResultGenerator.genFailResult("验证码错误"); }
String ref = request.getHeader("Referer"); if (!StringUtils.hasText(ref)) { return ResultGenerator.genFailResult("非法请求"); } if (null == newsId || newsId < 0) { return ResultGenerator.genFailResult("非法请求"); } if (!StringUtils.hasText(commentator)) { return ResultGenerator.genFailResult("请输入称呼"); } if (!StringUtils.hasText(commentBody)) { return ResultGenerator.genFailResult("请输入评论内容"); } if (commentBody.trim().length() > 200) { return ResultGenerator.genFailResult("评论内容过长"); } NewsComment comment = new NewsComment(); comment.setNewsId(newsId); comment.setCommentator(AntiXssUtils.cleanString(commentator)); comment.setCommentBody(AntiXssUtils.cleanString(commentBody)); session.removeAttribute("verifyCode");//留言成功后删除session中的验证码信息 return ResultGenerator.genSuccessResult(commentService.addComment(comment)); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\index\IndexController.java
2
请完成以下Spring Boot application配置
# to keep the JVM running camel.springboot.main-run-controller = true #configure the URL of the remote ActiveMQ broker #camel.component.activemq.broker-url=tcp://localhost:61616 #spring.activemq.broker-url
=tcp://localhost:61616 spring.activemq.in-memory=true spring.activemq.pool.enabled=false
repos\tutorials-master\patterns-modules\enterprise-patterns\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
protected void updateDeviceCredentials(TenantId tenantId, DeviceCredentialsUpdateMsg deviceCredentialsUpdateMsg) { DeviceCredentials deviceCredentials = JacksonUtil.fromString(deviceCredentialsUpdateMsg.getEntity(), DeviceCredentials.class, true); if (deviceCredentials == null) { throw new RuntimeException("[{" + tenantId + "}] deviceCredentialsUpdateMsg {" + deviceCredentialsUpdateMsg + "} cannot be converted to device credentials"); } Device device = edgeCtx.getDeviceService().findDeviceById(tenantId, deviceCredentials.getDeviceId()); if (device != null) { log.debug("[{}] Updating device credentials for device [{}]. New device credentials Id [{}], value [{}]", tenantId, device.getName(), deviceCredentials.getCredentialsId(), deviceCredentials.getCredentialsValue()); try { DeviceCredentials deviceCredentialsByDeviceId = edgeCtx.getDeviceCredentialsService().findDeviceCredentialsByDeviceId(tenantId, device.getId()); if (deviceCredentialsByDeviceId == null) { deviceCredentialsByDeviceId = new DeviceCredentials(); deviceCredentialsByDeviceId.setDeviceId(device.getId()); } deviceCredentialsByDeviceId.setCredentialsType(deviceCredentials.getCredentialsType()); deviceCredentialsByDeviceId.setCredentialsId(deviceCredentials.getCredentialsId()); deviceCredentialsByDeviceId.setCredentialsValue(deviceCredentials.getCredentialsValue()); edgeCtx.getDeviceCredentialsService().updateDeviceCredentials(tenantId, deviceCredentialsByDeviceId); } catch (Exception e) { log.error("[{}] Can't update device credentials for device [{}], deviceCredentialsUpdateMsg [{}]", tenantId, device.getName(), deviceCredentialsUpdateMsg, e); throw new RuntimeException(e); }
} else { log.warn("[{}] Can't find device by id [{}], deviceCredentialsUpdateMsg [{}]", tenantId, deviceCredentials.getDeviceId(), deviceCredentialsUpdateMsg); } } protected abstract void setCustomerId(TenantId tenantId, CustomerId customerId, Device device, DeviceUpdateMsg deviceUpdateMsg); protected void deleteDevice(TenantId tenantId, DeviceId deviceId) { deleteDevice(tenantId, null, deviceId); } protected void deleteDevice(TenantId tenantId, Edge edge, DeviceId deviceId) { Device deviceById = edgeCtx.getDeviceService().findDeviceById(tenantId, deviceId); if (deviceById != null) { edgeCtx.getDeviceService().deleteDevice(tenantId, deviceId); pushEntityEventToRuleEngine(tenantId, edge, deviceById, TbMsgType.ENTITY_DELETED); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\device\BaseDeviceProcessor.java
2
请完成以下Spring Boot application配置
# = Logging # Level for loggers on classes inside the root package "netgloo" (and its # sub-packages). # Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF logging.level.netgloo = DEBUG # Fine-tuning a specific logger (for a single class) # logging.level.netgloo.controllers.HomeController = TRACE # Specify the level for spring boot and hibernate's loggers logging.level.org.sprin
gframework.web = DEBUG # logging.level.org.hibernate = ERROR # Log file location (in addition to the console) #logging.file = /var/netgloo_blog/logs/spring-boot-logging.log
repos\spring-boot-samples-master\spring-boot-logging\src\main\resources\application.properties
2
请完成以下Java代码
private synchronized void add( @NonNull final DataItemId dataItemId, @NonNull final Collection<CacheKey> cacheKeys, @NonNull final Collection<TableRecordReference> recordRefs) { logger.debug("Adding to index: {} -> {}", dataItemId, cacheKeys); _dataItemId_to_cacheKey.putAll(dataItemId, cacheKeys); logger.debug("Adding to index: {} -> {}", recordRefs, dataItemId); recordRefs.forEach(recordRef -> _recordRef_to_dateItemId.put(recordRef, dataItemId)); } public void remove(final CacheKey cacheKey, final DataItem dataItem) { final DataItemId dataItemId = extractDataItemId(dataItem); final Collection<TableRecordReference> recordRefs = extractRecordRefs(dataItem); removeDataItemId(dataItemId, cacheKey, recordRefs); } private synchronized void removeDataItemId( final DataItemId dataItemId,
final CacheKey cacheKey, final Collection<TableRecordReference> recordRefs) { logger.debug("Removing pair from index: {}, {}", dataItemId, cacheKey); _dataItemId_to_cacheKey.remove(dataItemId, cacheKey); logger.debug("Removing pairs from index: {}, {}", recordRefs, dataItemId); recordRefs.forEach(recordRef -> _recordRef_to_dateItemId.remove(recordRef, dataItemId)); } @Override public boolean isResetAll(final TableRecordReference recordRef) { return adapter.isResetAll(recordRef); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheIndex.java
1
请完成以下Java代码
public TemplateType getType() { return type; } public void setType(TemplateType type) { this.type = type; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TemplateDefinition that = (TemplateDefinition) o; return ( Objects.equals(from, that.from) && Objects.equals(subject, that.subject) && type == that.type && Objects.equals(value, that.value) ); } @Override public int hashCode() { return Objects.hash(from, subject, type, value);
} @Override public String toString() { return ( "TemplateDefinition{" + "from='" + from + '\'' + ", subject='" + subject + '\'' + ", type=" + type + ", value='" + value + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TemplateDefinition.java
1