instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void removePausesAroundTimeframe( @NonNull final I_C_Flatrate_Term term, @NonNull final Timestamp pauseFrom, @NonNull final Timestamp pauseUntil) { new RemovePauses(this).removePausesAroundTimeframe(term, pauseFrom, pauseUntil); resetCache(BPartnerId.ofRepoId(term.getBill_BPartner_ID()), FlatrateDataId.ofRepoId(term.getC_Flatrate_Data_ID())); } public void removePausesAroundDate( @NonNull final I_C_Flatrate_Term term, @NonNull final Timestamp date) { new RemovePauses(this).removePausesAroundTimeframe(term, date, date); resetCache(BPartnerId.ofRepoId(term.getBill_BPartner_ID()), FlatrateDataId.ofRepoId(term.getC_Flatrate_Data_ID())); } public void removeAllPauses(final I_C_Flatrate_Term term) { final Timestamp distantPast = TimeUtil.getDay(1970, 1, 1); final Timestamp distantFuture = TimeUtil.getDay(9999, 12, 31); new RemovePauses(this).removePausesAroundTimeframe(term, distantPast, distantFuture); resetCache(BPartnerId.ofRepoId(term.getBill_BPartner_ID()), FlatrateDataId.ofRepoId(term.getC_Flatrate_Data_ID())); } public final List<I_C_SubscriptionProgress> retrieveNextSPsAndLogIfEmpty( @NonNull final I_C_Flatrate_Term term, @NonNull final Timestamp pauseFrom) { final ISubscriptionDAO subscriptionDAO = Services.get(ISubscriptionDAO.class); final SubscriptionProgressQuery query = SubscriptionProgressQuery.builder() .term(term) .eventDateNotBefore(pauseFrom) .build(); final List<I_C_SubscriptionProgress> sps = subscriptionDAO.retrieveSubscriptionProgresses(query); if (sps.isEmpty()) { final IMsgBL msgBL = Services.get(IMsgBL.class); Loggables.addLog(msgBL.getMsg(Env.getCtx(), MSG_NO_SPS_AFTER_DATE_1P, new Object[] { pauseFrom }));
} return sps; } /** * This is needed because no direct parent-child relationship can be established between these tables, as the {@code I_C_SubscriptionProgress} tabs would want to show * records for which the C_BPartner_ID in context is either the recipient or the contract holder. */ private static void resetCache(@NonNull final BPartnerId bpartnerId, @NonNull final FlatrateDataId flatrateDataId) { final ModelCacheInvalidationService modelCacheInvalidationService = ModelCacheInvalidationService.get(); modelCacheInvalidationService.invalidate( CacheInvalidateMultiRequest.of( CacheInvalidateRequest.allChildRecords(I_C_Flatrate_Data.Table_Name, flatrateDataId, I_C_SubscriptionProgress.Table_Name), CacheInvalidateRequest.allChildRecords(I_C_BPartner.Table_Name, bpartnerId, I_C_SubscriptionProgress.Table_Name)), ModelCacheInvalidationTiming.AFTER_CHANGE ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\SubscriptionService.java
1
请在Spring Boot框架中完成以下Java代码
public ItemWriter<Canton> writer(DruidDataSource dataSource) { JdbcBatchItemWriter<Canton> writer = new JdbcBatchItemWriter<>(); //我们使用JDBC批处理的JdbcBatchItemWriter来写数据到数据库 writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()); String sql = "insert into nt_bsc_Canton " + " (f_id,f_code,f_name,f_parentid,f_financial,f_contactman,f_tel,f_email,f_cantonlev,f_taxorgcode,f_memo,f_using,f_usingdate,f_level,f_end,f_qrcantonid,f_declare,f_declareisend) " + " values(:id,:code,:name,:parentid,:financial,:contactman,:tel,:email,:cantonlev,:taxorgcode,:memo,:using,:usingdate,:level,:end,:qrcantonid,:declare,:declareisend)"; //在此设置要执行批处理的SQL语句 writer.setSql(sql); writer.setDataSource(dataSource); return writer; } /** * Job定义,我们要实际执行的任务,包含一个或多个Step * * @param jobBuilderFactory * @param s1 * @return */ @Bean(name = "cantonJob") public Job cantonJob(JobBuilderFactory jobBuilderFactory, @Qualifier("cantonStep1") Step s1) { return jobBuilderFactory.get("cantonJob") .incrementer(new RunIdIncrementer()) .flow(s1)//为Job指定Step .end() .listener(new MyJobListener())//绑定监听器csvJobListener .build(); } /** * step步骤,包含ItemReader,ItemProcessor和ItemWriter * * @param stepBuilderFactory * @param reader * @param writer * @param processor * @return */
@Bean(name = "cantonStep1") public Step cantonStep1(StepBuilderFactory stepBuilderFactory, @Qualifier("cantonReader") ItemReader<Canton> reader, @Qualifier("cantonWriter") ItemWriter<Canton> writer, @Qualifier("cantonProcessor") ItemProcessor<Canton, Canton> processor) { return stepBuilderFactory .get("cantonStep1") .<Canton, Canton>chunk(5000)//批处理每次提交5000条数据 .reader(reader)//给step绑定reader .processor(processor)//给step绑定processor .writer(writer)//给step绑定writer .faultTolerant() .retry(Exception.class) // 重试 .noRetry(ParseException.class) .retryLimit(1) //每条记录重试一次 .skip(Exception.class) .skipLimit(200) //一共允许跳过200次异常 // .taskExecutor(new SimpleAsyncTaskExecutor()) //设置每个Job通过并发方式执行,一般来讲一个Job就让它串行完成的好 // .throttleLimit(10) //并发任务数为 10,默认为4 .build(); } @Bean public Validator<Canton> csvBeanValidator() { return new MyBeanValidator<>(); } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\CantonConfig.java
2
请完成以下Java代码
public List<IOParameter> getInParameters() { return inParameters; } @Override public void addInParameter(IOParameter inParameter) { inParameters.add(inParameter); } @Override public void setInParameters(List<IOParameter> inParameters) { this.inParameters = inParameters; } @Override public List<IOParameter> getOutParameters() { return outParameters; } @Override public void addOutParameter(IOParameter outParameter) { this.outParameters.add(outParameter); } @Override public void setOutParameters(List<IOParameter> outParameters) { this.outParameters = outParameters; } public String getCaseInstanceIdVariableName() { return caseInstanceIdVariableName; } public void setCaseInstanceIdVariableName(String caseInstanceIdVariableName) { this.caseInstanceIdVariableName = caseInstanceIdVariableName; } @Override public CaseServiceTask clone() { CaseServiceTask clone = new CaseServiceTask();
clone.setValues(this); return clone; } public void setValues(CaseServiceTask otherElement) { super.setValues(otherElement); setCaseDefinitionKey(otherElement.getCaseDefinitionKey()); setCaseInstanceName(otherElement.getCaseInstanceName()); setBusinessKey(otherElement.getBusinessKey()); setInheritBusinessKey(otherElement.isInheritBusinessKey()); setSameDeployment(otherElement.isSameDeployment()); setFallbackToDefaultTenant(otherElement.isFallbackToDefaultTenant()); setCaseInstanceIdVariableName(otherElement.getCaseInstanceIdVariableName()); inParameters = new ArrayList<>(); if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } outParameters = new ArrayList<>(); if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) { for (IOParameter parameter : otherElement.getOutParameters()) { outParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CaseServiceTask.java
1
请在Spring Boot框架中完成以下Java代码
public class ThreadLocalDataHelper { /** * 线程的本地变量 */ private static final ThreadLocal<ConcurrentHashMap> REQUEST_DATA = new ThreadLocal<>(); /** * 存储本地参数 */ private static final ConcurrentHashMap DATA_MAP = new ConcurrentHashMap<>(); /** * 设置请求参数 * * @param key 参数key * @param value 参数值 */ public static void put(String key, Object value) { if(ObjectUtil.isNotEmpty(value)) { DATA_MAP.put(key, value); REQUEST_DATA.set(DATA_MAP); } } /** * 获取请求参数值 * * @param key 请求参数
* @return */ public static <T> T get(String key) { ConcurrentHashMap dataMap = REQUEST_DATA.get(); if (CollectionUtils.isNotEmpty(dataMap)) { return (T) dataMap.get(key); } return null; } /** * 获取请求参数 * * @return 请求参数 MAP 对象 */ public static void clear() { DATA_MAP.clear(); REQUEST_DATA.remove(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\mybatis\ThreadLocalDataHelper.java
2
请在Spring Boot框架中完成以下Java代码
public class CreateInvoiceForModelService { private final IAsyncBatchBL asyncBatchBL = Services.get(IAsyncBatchBL.class); private final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); private final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); private final AsyncBatchService asyncBatchService; public CreateInvoiceForModelService( @NonNull final AsyncBatchService asyncBatchService) { this.asyncBatchService = asyncBatchService; } /** * Uses the Async-framework to create invoice candidates for the given model. Waits until those candidates are created and then enqueues them for invoicing. * * @param modelReferences the models for which the invoice candidates and subsequently invoice(s) shall be created. */ public void generateIcsAndInvoices(@NonNull final List<TableRecordReference> modelReferences) { generateMissingInvoiceCandidatesForModel(modelReferences); final HashSet<InvoiceCandidateId> invoiceCandidateIds = new HashSet<>(); for (final TableRecordReference modelReference : modelReferences) { invoiceCandidateIds.addAll(invoiceCandDAO.retrieveReferencingIds(modelReference)); } final PInstanceId invoiceCandidatesSelectionId = DB.createT_Selection(invoiceCandidateIds, Trx.TRXNAME_None); invoiceCandBL.enqueueForInvoicing() .setContext(getCtx()) .setInvoicingParams(createDefaultIInvoicingParams()) .setFailIfNothingEnqueued(true) .prepareAndEnqueueSelection(invoiceCandidatesSelectionId); } private void generateMissingInvoiceCandidatesForModel(@NonNull final List<TableRecordReference> modelReferences) {
final List<Object> models = TableRecordReference.getModels(modelReferences, Object.class); final Multimap<AsyncBatchId, Object> batchIdWithUpdatedModel = asyncBatchBL.assignTempAsyncBatchToModelsIfMissing( models, Async_Constants.C_Async_Batch_InternalName_EnqueueInvoiceCandidateCreation); for (final AsyncBatchId asyncBatchId : batchIdWithUpdatedModel.keySet()) { final Collection<Object> modelsWithBatchId = batchIdWithUpdatedModel.get(asyncBatchId); final Supplier<IEnqueueResult> action = () -> { int counter = 0; for (final Object modelWithBatchId : modelsWithBatchId) { CreateMissingInvoiceCandidatesWorkpackageProcessor.schedule(modelWithBatchId); counter++; } final int finalCounter = counter; // a lambda's return value should be final return () -> finalCounter; // return the numer of workpackages that we enqeued }; asyncBatchService.executeBatch(action, asyncBatchId); } } @NonNull private IInvoicingParams createDefaultIInvoicingParams() { final PlainInvoicingParams invoicingParams = new PlainInvoicingParams(); invoicingParams.setIgnoreInvoiceSchedule(false); invoicingParams.setDateInvoiced(LocalDate.now()); return invoicingParams; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\CreateInvoiceForModelService.java
2
请完成以下Java代码
public class FilterQueryImpl extends AbstractQuery<FilterQuery, Filter> implements FilterQuery { private static final long serialVersionUID = 1L; protected String filterId; protected String resourceType; protected String name; protected String nameLike; protected String owner; public FilterQueryImpl() { } public FilterQueryImpl(CommandExecutor commandExecutor) { super(commandExecutor); } public FilterQuery filterId(String filterId) { ensureNotNull("filterId", filterId); this.filterId = filterId; return this; } public FilterQuery filterResourceType(String resourceType) { ensureNotNull("resourceType", resourceType); this.resourceType = resourceType; return this; } public FilterQuery filterName(String name) { ensureNotNull("name", name); this.name = name; return this; } public FilterQuery filterNameLike(String nameLike) { ensureNotNull("nameLike", nameLike); this.nameLike = nameLike; return this; }
public FilterQuery filterOwner(String owner) { ensureNotNull("owner", owner); this.owner = owner; return this; } public FilterQuery orderByFilterId() { return orderBy(FilterQueryProperty.FILTER_ID); } public FilterQuery orderByFilterResourceType() { return orderBy(FilterQueryProperty.RESOURCE_TYPE); } public FilterQuery orderByFilterName() { return orderBy(FilterQueryProperty.NAME); } public FilterQuery orderByFilterOwner() { return orderBy(FilterQueryProperty.OWNER); } public List<Filter> executeList(CommandContext commandContext, Page page) { return commandContext .getFilterManager() .findFiltersByQueryCriteria(this); } public long executeCount(CommandContext commandContext) { return commandContext .getFilterManager() .findFilterCountByQueryCriteria(this); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\filter\FilterQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ClientServiceImpl implements ClientService { private static final Logger LOG = LoggerFactory.getLogger(ClientServiceImpl.class); private final PrintService printService; private final PrintService printServiceErr; private final PrintService printServiceOut; private final DataService dataService; private final DataService dataServicePrototype; public ClientServiceImpl(@Autowired PrintService printService, @Autowired @Qualifier("stdErr") PrintService printServiceErr, @Autowired @Qualifier("stdOut") PrintService printServiceOut, @Autowired DataService dataService, @Autowired @Qualifier("prototype") DataService dataServicePrototype) { this.printService = printService; this.printServiceErr = printServiceErr; this.printServiceOut = printServiceOut; this.dataService = dataService; this.dataServicePrototype = dataServicePrototype; } @PostConstruct public void init() { LOG.info("init ..."); printService.print("init ..."); printServiceErr.print("init ...."); printService.print(dataService.getData()); printServiceOut.print("init ....."); } @Override public String printDefault(String message) { return printService.print(message); } @Override public String printStdErr(String message) { return printServiceErr.print(message); } @Override public String printStdOut(String message) {
return printServiceOut.print(message); } @Override public String getData() { return dataService.getData(); } @Override public String getDataPrototype() { return dataServicePrototype.getData(); } @PreDestroy public void shutdown() { LOG.info("##destroy."); } }
repos\spring-examples-java-17\spring-di\src\main\java\itx\examples\springboot\di\services\ClientServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public InMemoryUserDetailsManager userDetailsService() { UserDetails user = User.withUsername("user1") .password("{noop}user1Pass") .authorities("ROLE_USER") .build(); UserDetails admin = User.withUsername("admin1") .password("{noop}admin1Pass") .authorities("ROLE_ADMIN") .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth.requestMatchers("/anonymous*") .anonymous() .requestMatchers("/login*") .permitAll()
.anyRequest() .authenticated()) .formLogin(formLogin -> formLogin.loginPage("/login.html") .loginProcessingUrl("/login") .successHandler(myAuthenticationSuccessHandler()) .failureUrl("/login.html?error=true")) .rememberMe(rememberMe -> rememberMe.key("uniqueAndSecret") .tokenValiditySeconds(86400)) .logout(logout -> logout.deleteCookies("JSESSIONID")) .csrf(AbstractHttpConfigurer::disable); return http.build(); } @Bean public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){ return new MySimpleUrlAuthenticationSuccessHandler(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\spring\SecSecurityConfig.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getJoinDate() { return joinDate; } public void setJoinDate(Date joinDate) { this.joinDate = joinDate; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-annotations-2\src\main\java\com\baeldung\queryhint\Employee.java
1
请完成以下Java代码
public void setMigrationDate (java.sql.Timestamp MigrationDate) { set_Value (COLUMNNAME_MigrationDate, MigrationDate); } /** Get Migriert am. @return Migriert am */ @Override public java.sql.Timestamp getMigrationDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_MigrationDate); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Mitteilung. @param TextMsg Text Message */ @Override public void setTextMsg (java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Mitteilung. @return Text Message
*/ @Override public java.lang.String getTextMsg () { return (java.lang.String)get_Value(COLUMNNAME_TextMsg); } /** Set Titel. @param Title Name this entity is referred to as */ @Override public void setTitle (java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Titel. @return Name this entity is referred to as */ @Override public java.lang.String getTitle () { return (java.lang.String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment.java
1
请完成以下Java代码
private static class X509CertificateDecoder implements Converter<List<String>, RSAPublicKey> { private final CertificateFactory certificateFactory; X509CertificateDecoder(CertificateFactory certificateFactory) { this.certificateFactory = certificateFactory; } @Override public @NonNull RSAPublicKey convert(List<String> lines) { StringBuilder base64Encoded = new StringBuilder(); for (String line : lines) { if (isNotX509CertificateWrapper(line)) { base64Encoded.append(line); } } byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString()); try (InputStream x509CertStream = new ByteArrayInputStream(x509)) {
X509Certificate certificate = (X509Certificate) this.certificateFactory .generateCertificate(x509CertStream); return (RSAPublicKey) certificate.getPublicKey(); } catch (CertificateException | IOException ex) { throw new IllegalArgumentException(ex); } } private boolean isNotX509CertificateWrapper(String line) { return !X509_CERT_HEADER.equals(line) && !X509_CERT_FOOTER.equals(line); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\converter\RsaKeyConverters.java
1
请完成以下Java代码
public class ByteArrayValueMapper extends PrimitiveValueMapper<BytesValue> { public ByteArrayValueMapper() { super(ValueType.BYTES); } public BytesValue convertToTypedValue(UntypedValueImpl untypedValue) { byte[] byteArr; Object value = untypedValue.getValue(); if (value instanceof byte[]) { byteArr = (byte[]) value; } else { byteArr = IoUtil.inputStreamAsByteArray((InputStream) value); } return Variables.byteArrayValue(byteArr); } public BytesValue readValue(TypedValueField typedValueField) { byte[] byteArr = null; String value = (String) typedValueField.getValue(); if (value != null) { byteArr = Base64.decodeBase64(value); } return Variables.byteArrayValue(byteArr); } public void writeValue(BytesValue byteValue, TypedValueField typedValueField) { byte[] bytes = byteValue.getValue();
if (bytes != null) { typedValueField.setValue(Base64.encodeBase64String(bytes)); } } protected boolean canWriteValue(TypedValue typedValue) { Object value = typedValue.getValue(); return super.canWriteValue(typedValue) || value instanceof InputStream; } protected boolean canReadValue(TypedValueField typedValueField) { Object value = typedValueField.getValue(); return value == null || value instanceof String; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\mapper\ByteArrayValueMapper.java
1
请完成以下Java代码
public class InvoiceLineQuickInputProcessor implements IQuickInputProcessor { private final IHUPackingAwareBL huPackingAwareBL = Services.get(IHUPackingAwareBL.class); private final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); private final IInvoiceLineBL invoiceLineBL = Services.get(IInvoiceLineBL.class); private final IBPartnerProductBL partnerProductBL = Services.get(IBPartnerProductBL.class); @Override public Set<DocumentId> process(final QuickInput quickInput) { final I_C_Invoice invoice = quickInput.getRootDocumentAs(I_C_Invoice.class); final IInvoiceLineQuickInput invoiceLineQuickInput = quickInput.getQuickInputDocumentAs(IInvoiceLineQuickInput.class); // 3834 final ProductId productId = ProductId.ofRepoId(invoiceLineQuickInput.getM_Product_ID()); final BPartnerId partnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID()); final SOTrx soTrx = SOTrx.ofBooleanNotNull(invoice.isSOTrx()); partnerProductBL.assertNotExcludedFromTransaction(soTrx, productId, partnerId); final I_C_InvoiceLine invoiceLine = InterfaceWrapperHelper.newInstance(I_C_InvoiceLine.class, invoice); invoiceLine.setC_Invoice(invoice); invoiceBL.setProductAndUOM(invoiceLine, productId);
final PlainHUPackingAware huPackingAware = new PlainHUPackingAware(); huPackingAware.setBpartnerId(partnerId); huPackingAware.setInDispute(false); huPackingAware.setProductId(productId); huPackingAware.setUomId(UomId.ofRepoIdOrNull(invoiceLine.getC_UOM_ID())); huPackingAware.setPiItemProductId(invoiceLineQuickInput.getM_HU_PI_Item_Product_ID() > 0 ? HUPIItemProductId.ofRepoId(invoiceLineQuickInput.getM_HU_PI_Item_Product_ID()) : HUPIItemProductId.VIRTUAL_HU); huPackingAwareBL.computeAndSetQtysForNewHuPackingAware(huPackingAware, invoiceLineQuickInput.getQty()); huPackingAwareBL.prepareCopyFrom(huPackingAware) .overridePartner(false) .copyTo(InvoiceLineHUPackingAware.of(invoiceLine)); invoiceLineBL.updatePrices(invoiceLine); // invoiceBL.setLineNetAmt(invoiceLine); // not needed; will be called on save // invoiceBL.setTaxAmt(invoiceLine);// not needed; will be called on save InterfaceWrapperHelper.save(invoiceLine); final DocumentId documentId = DocumentId.of(invoiceLine.getC_InvoiceLine_ID()); return ImmutableSet.of(documentId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\invoiceline\InvoiceLineQuickInputProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public class EventGeneratedId { @Id @Column(name = "event_generated_id") @GeneratedValue(generator = "increment") @GenericGenerator(name = "increment", strategy = "increment") private Long id; @Column(name = "name") private String name; @Column(name = "description") private String description; public EventGeneratedId() { } public EventGeneratedId(String name, String description) { this.name = name; this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\immutable\entities\EventGeneratedId.java
2
请完成以下Java代码
public static <T> T postApplicationXWwwFormUrlencoded(String url, Object param, String interfaceName, Class<T> clazz) { Map<String, String> paramMap = JSON.parseObject(JSON.toJSONString(param), new TypeReference<Map<String, String>>() { }); // 生成requestBody StringBuilder content = new StringBuilder(128); for (Map.Entry<String, String> entry : paramMap.entrySet()) { content.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } if (content.length() > 0) { content.deleteCharAt(content.length() - 1); } RequestBody requestBody = FormBody.create(MediaType.parse("application/x-www-form-urlencoded"), content.toString()); return post(url, interfaceName, requestBody, param, clazz); } /** * 发起post请求,不做任何签名 * * @param url 发送请求的URL * @param interfaceName 接口名称 * @param requestBody 请求体 * @param param 参数 * @throws IOException */ public static <T> T post(String url, String interfaceName, RequestBody requestBody, Object param, Class<T> clazz) { Request request = new Request.Builder() //请求的url .url(url) .post(requestBody) .build(); Response response = null; String result = ""; String errorMsg = "";
try { //创建/Call response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) { logger.error("访问外部系统异常 {}: {}", url, response.toString()); errorMsg = String.format("访问外部系统异常:%s", response.toString()); throw new RemoteAccessException(errorMsg); } result = response.body().string(); } catch (RemoteAccessException e) { logger.warn(e.getMessage(), e); result = e.getMessage(); throw e; } catch (Exception e) { logger.warn(e.getMessage(), e); if (Objects.isNull(response)) { errorMsg = String.format("访问外部系统异常::%s", e.getMessage()); throw new RemoteAccessException(errorMsg, e); } errorMsg = String.format("访问外部系统异常:::%s", response.toString()); throw new RemoteAccessException(errorMsg, e); } finally { logger.info("请求 {} {},请求参数:{}, 返回参数:{}", interfaceName, url, JSON.toJSONString(param), StringUtils.isEmpty(result) ? errorMsg : result); } return JSON.parseObject(result, clazz); } }
repos\spring-boot-student-master\spring-boot-student-okhttp\src\main\java\com\xiaolyuh\util\OkHttpClientUtil.java
1
请完成以下Java代码
public void insertProcessDefinitionInfo(ProcessDefinitionInfoEntity processDefinitionInfo) { insert(processDefinitionInfo); } public void updateProcessDefinitionInfo(ProcessDefinitionInfoEntity updatedProcessDefinitionInfo) { update(updatedProcessDefinitionInfo, true); } public void deleteProcessDefinitionInfo(String processDefinitionId) { ProcessDefinitionInfoEntity processDefinitionInfo = findProcessDefinitionInfoByProcessDefinitionId( processDefinitionId ); if (processDefinitionInfo != null) { delete(processDefinitionInfo); deleteInfoJson(processDefinitionInfo); } } public void updateInfoJson(String id, byte[] json) { ProcessDefinitionInfoEntity processDefinitionInfo = findById(id); if (processDefinitionInfo != null) { ByteArrayRef ref = new ByteArrayRef(processDefinitionInfo.getInfoJsonId()); ref.setValue("json", json); if (processDefinitionInfo.getInfoJsonId() == null) { processDefinitionInfo.setInfoJsonId(ref.getId()); updateProcessDefinitionInfo(processDefinitionInfo); }
} } public void deleteInfoJson(ProcessDefinitionInfoEntity processDefinitionInfo) { if (processDefinitionInfo.getInfoJsonId() != null) { ByteArrayRef ref = new ByteArrayRef(processDefinitionInfo.getInfoJsonId()); ref.delete(); } } public ProcessDefinitionInfoEntity findProcessDefinitionInfoByProcessDefinitionId(String processDefinitionId) { return processDefinitionInfoDataManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId); } public byte[] findInfoJsonById(String infoJsonId) { ByteArrayRef ref = new ByteArrayRef(infoJsonId); return ref.getBytes(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionInfoEntityManagerImpl.java
1
请完成以下Java代码
private static ExplainedOptional<Plan> createPlan(@NonNull final ImmutableList<PaymentRow> paymentRows) { if (paymentRows.size() != 1) { return ExplainedOptional.emptyBecause("Only one payment row can be selected for write-off"); } final PaymentRow paymentRow = CollectionUtils.singleElement(paymentRows); final Amount openAmt = paymentRow.getOpenAmt(); if (openAmt.signum() == 0) { return ExplainedOptional.emptyBecause("Zero open amount. Nothing to write-off"); } return ExplainedOptional.of(
Plan.builder() .paymentId(paymentRow.getPaymentId()) .amtMultiplier(paymentRow.getPaymentAmtMultiplier()) .amountToWriteOff(openAmt) .build()); } @Value @Builder private static class Plan { @NonNull PaymentId paymentId; @NonNull PaymentAmtMultiplier amtMultiplier; @NonNull Amount amountToWriteOff; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_PaymentWriteOff.java
1
请在Spring Boot框架中完成以下Java代码
public LineItemReference lineItemId(String lineItemId) { this.lineItemId = lineItemId; return this; } /** * This is the unique identifier of the eBay order line item that is part of the shipping fulfillment. The line item ID is created as soon as there is a commitment to buy from the seller. * * @return lineItemId **/ @javax.annotation.Nullable @ApiModelProperty(value = "This is the unique identifier of the eBay order line item that is part of the shipping fulfillment. The line item ID is created as soon as there is a commitment to buy from the seller.") public String getLineItemId() { return lineItemId; } public void setLineItemId(String lineItemId) { this.lineItemId = lineItemId; } public LineItemReference quantity(Integer quantity) { this.quantity = quantity; return this; } /** * This field is reserved for internal or future use. * * @return quantity **/ @javax.annotation.Nullable @ApiModelProperty(value = "This field is reserved for internal or future use.") public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) {
return false; } LineItemReference lineItemReference = (LineItemReference)o; return Objects.equals(this.lineItemId, lineItemReference.lineItemId) && Objects.equals(this.quantity, lineItemReference.quantity); } @Override public int hashCode() { return Objects.hash(lineItemId, quantity); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LineItemReference {\n"); sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LineItemReference.java
2
请完成以下Java代码
public void setDeactivationReason (final @Nullable String DeactivationReason) { set_Value (COLUMNNAME_DeactivationReason, DeactivationReason); } @Override public String getDeactivationReason() { return get_ValueAsString(COLUMNNAME_DeactivationReason); } @Override public void setDischargeDate (final @Nullable java.sql.Timestamp DischargeDate) { set_Value (COLUMNNAME_DischargeDate, DischargeDate); } @Override public java.sql.Timestamp getDischargeDate() { return get_ValueAsTimestamp(COLUMNNAME_DischargeDate); } @Override public void setIsIVTherapy (final boolean IsIVTherapy) { set_Value (COLUMNNAME_IsIVTherapy, IsIVTherapy); } @Override public boolean isIVTherapy() { return get_ValueAsBoolean(COLUMNNAME_IsIVTherapy); } @Override public void setIsTransferPatient (final boolean IsTransferPatient) { set_Value (COLUMNNAME_IsTransferPatient, IsTransferPatient); } @Override public boolean isTransferPatient() { return get_ValueAsBoolean(COLUMNNAME_IsTransferPatient); } @Override public void setNumberOfInsured (final @Nullable String NumberOfInsured) { set_Value (COLUMNNAME_NumberOfInsured, NumberOfInsured);
} @Override public String getNumberOfInsured() { return get_ValueAsString(COLUMNNAME_NumberOfInsured); } /** * PayerType AD_Reference_ID=541319 * Reference name: PayerType_list */ public static final int PAYERTYPE_AD_Reference_ID=541319; /** Unbekannt = 0 */ public static final String PAYERTYPE_Unbekannt = "0"; /** Gesetzlich = 1 */ public static final String PAYERTYPE_Gesetzlich = "1"; /** Privat = 2 */ public static final String PAYERTYPE_Privat = "2"; /** Berufsgenossenschaft = 3 */ public static final String PAYERTYPE_Berufsgenossenschaft = "3"; /** Selbstzahler = 4 */ public static final String PAYERTYPE_Selbstzahler = "4"; /** Andere = 5 */ public static final String PAYERTYPE_Andere = "5"; @Override public void setPayerType (final @Nullable String PayerType) { set_Value (COLUMNNAME_PayerType, PayerType); } @Override public String getPayerType() { return get_ValueAsString(COLUMNNAME_PayerType); } @Override public void setUpdatedAt (final @Nullable java.sql.Timestamp UpdatedAt) { set_Value (COLUMNNAME_UpdatedAt, UpdatedAt); } @Override public java.sql.Timestamp getUpdatedAt() { return get_ValueAsTimestamp(COLUMNNAME_UpdatedAt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_AlbertaPatient.java
1
请完成以下Java代码
public String[] getCaseActivityIds() { return caseActivityIds; } public boolean isTenantIdSet() { return isTenantIdSet; } public String getVariableName() { return variableName; } public String getVariableNameLike() { return variableNameLike; } public QueryVariableValue getQueryVariableValue() { return queryVariableValue; } public Boolean getVariableNamesIgnoreCase() { return variableNamesIgnoreCase; } public Boolean getVariableValuesIgnoreCase() { return variableValuesIgnoreCase; } @Override public HistoricVariableInstanceQuery includeDeleted() { includeDeleted = true; return this;
} public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public List<String> getVariableNameIn() { return variableNameIn; } public Date getCreatedAfter() { return createdAfter; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricVariableInstanceQueryImpl.java
1
请完成以下Java代码
public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPlannedAmt (final BigDecimal PlannedAmt) { set_Value (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedMarginAmt (final BigDecimal PlannedMarginAmt) { set_Value (COLUMNNAME_PlannedMarginAmt, PlannedMarginAmt); } @Override public BigDecimal getPlannedMarginAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedMarginAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedPrice (final BigDecimal PlannedPrice) { set_Value (COLUMNNAME_PlannedPrice, PlannedPrice); } @Override
public BigDecimal getPlannedPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedPrice); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedQty (final BigDecimal PlannedQty) { set_Value (COLUMNNAME_PlannedQty, PlannedQty); } @Override public BigDecimal getPlannedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectLine.java
1
请完成以下Java代码
public Object execute(ScriptEngine scriptEngine, VariableScope variableScope, Bindings bindings) { return evaluate(scriptEngine, variableScope, bindings); } protected String getActivityIdExceptionMessage(VariableScope variableScope) { String activityId = null; String definitionIdMessage = ""; if (variableScope instanceof DelegateExecution) { activityId = ((DelegateExecution) variableScope).getCurrentActivityId(); definitionIdMessage = " in the process definition with id '" + ((DelegateExecution) variableScope).getProcessDefinitionId() + "'"; } else if (variableScope instanceof TaskEntity) { TaskEntity task = (TaskEntity) variableScope; if (task.getExecution() != null) { activityId = task.getExecution().getActivityId(); definitionIdMessage = " in the process definition with id '" + task.getProcessDefinitionId() + "'"; } if (task.getCaseExecution() != null) { activityId = task.getCaseExecution().getActivityId();
definitionIdMessage = " in the case definition with id '" + task.getCaseDefinitionId() + "'"; } } else if (variableScope instanceof DelegateCaseExecution) { activityId = ((DelegateCaseExecution) variableScope).getActivityId(); definitionIdMessage = " in the case definition with id '" + ((DelegateCaseExecution) variableScope).getCaseDefinitionId() + "'"; } if (activityId == null) { return ""; } else { return " while executing activity '" + activityId + "'" + definitionIdMessage; } } protected abstract Object evaluate(ScriptEngine scriptEngine, VariableScope variableScope, Bindings bindings); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\ExecutableScript.java
1
请完成以下Java代码
public void clearFields(final GridTab gridTab) { final I_C_Order order = InterfaceWrapperHelper.create(gridTab, I_C_Order.class); order.setM_Product_ID(-1); order.setQty_FastInput(null); // these changes will be propagated to the GUI component gridTab.setValue(I_C_Order.COLUMNNAME_M_Product_ID, null); gridTab.setValue(I_C_Order.COLUMNNAME_Qty_FastInput, null); } @Override public boolean requestFocus(final GridTab gridTab) { final I_C_Order order = InterfaceWrapperHelper.create(gridTab, I_C_Order.class); final Integer productId = order.getM_Product_ID(); if (productId <= 0 && gridTab.getField(I_C_Order.COLUMNNAME_M_Product_ID).isDisplayed()) { gridTab.getField(I_C_Order.COLUMNNAME_M_Product_ID).requestFocus(); return true; } final BigDecimal qty = order.getQty_FastInput(); if (qty == null || qty.signum() <= 0 && gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput).isDisplayed()) {
// product has been set, but qty hasn't gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput).requestFocus(); return true; } // no focus was requested return false; } @Override public IGridTabRowBuilder createLineBuilderFromHeader(final Object model) { final OrderLineProductQtyGridRowBuilder builder = new OrderLineProductQtyGridRowBuilder(); builder.setSource(model); return builder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\ProductQtyOrderFastInputHandler.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public de.metas.order.model.I_C_CompensationGroup_Schema getC_CompensationGroup_Schema() { return get_ValueAsPO(COLUMNNAME_C_CompensationGroup_Schema_ID, de.metas.order.model.I_C_CompensationGroup_Schema.class); } @Override public void setC_CompensationGroup_Schema(final de.metas.order.model.I_C_CompensationGroup_Schema C_CompensationGroup_Schema) { set_ValueFromPO(COLUMNNAME_C_CompensationGroup_Schema_ID, de.metas.order.model.I_C_CompensationGroup_Schema.class, C_CompensationGroup_Schema); } @Override public void setC_CompensationGroup_Schema_ID (final int C_CompensationGroup_Schema_ID) { if (C_CompensationGroup_Schema_ID < 1) set_Value (COLUMNNAME_C_CompensationGroup_Schema_ID, null); else set_Value (COLUMNNAME_C_CompensationGroup_Schema_ID, C_CompensationGroup_Schema_ID); } @Override public int getC_CompensationGroup_Schema_ID() { return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_ID); } @Override public void setM_Product_Exclude_FlatrateConditions_ID (final int M_Product_Exclude_FlatrateConditions_ID) { if (M_Product_Exclude_FlatrateConditions_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Exclude_FlatrateConditions_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_Product_Exclude_FlatrateConditions_ID, M_Product_Exclude_FlatrateConditions_ID); } @Override public int getM_Product_Exclude_FlatrateConditions_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Exclude_FlatrateConditions_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Exclude_FlatrateConditions.java
1
请完成以下Java代码
public class SyncConfirmation { /** * Can be Set by the <b>receiver</b> to indicate the ID it sued to locally store the received data. */ private String serverEventId; /** * Shall be set by the <b>receiver</b> to indicate when the receiver actually confirmed the receipt of the sync data. */ private Date dateConfirmed; /** * Set by the <b>sender</b>, i.e. the party which waits for the confirmation. * It can be seen as a correlation-ID. */ private long confirmId; @Builder @JsonCreator private SyncConfirmation( @JsonProperty("serverEventId") final String serverEventId, @JsonProperty("dateConfirmed") final Date dateConfirmed, @JsonProperty("confirmId") final long confirmId)
{ this.serverEventId = serverEventId; this.dateConfirmed = dateConfirmed; this.confirmId = confirmId; } // */ /** * Shall be used by the remote/receiving endpoint to generate a confirmation instance. * * @param syncConfirmationId shall be taken from {@link IConfirmableDTO#getSyncConfirmationId()} which was received from the sending endpoint.<br> * The sending endpoint will know to correlate this instance with the sync package it send by using the ID. */ public static SyncConfirmation forConfirmId(final long syncConfirmationId) { return SyncConfirmation.builder().confirmId(syncConfirmationId).build(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\dto\SyncConfirmation.java
1
请完成以下Java代码
public void setValidating(boolean validating) { this.reader.setValidating(validating); } /** * {@inheritDoc} * <p> * Delegates the given environment to underlying {@link XmlBeanDefinitionReader}. * Should be called before any call to {@link #load}. */ @Override public void setEnvironment(ConfigurableEnvironment environment) { super.setEnvironment(environment); this.reader.setEnvironment(getEnvironment()); } /** * Load bean definitions from the given XML resources. * @param resources one or more resources to load from */ public final void load(Resource... resources) { this.reader.loadBeanDefinitions(resources); } /** * Load bean definitions from the given XML resources. * @param resourceLocations one or more resource locations to load from
*/ public final void load(String... resourceLocations) { this.reader.loadBeanDefinitions(resourceLocations); } /** * Load bean definitions from the given XML resources. * @param relativeClass class whose package will be used as a prefix when loading each * specified resource name * @param resourceNames relatively-qualified names of resources to load */ public final void load(Class<?> relativeClass, String... resourceNames) { Resource[] resources = new Resource[resourceNames.length]; for (int i = 0; i < resourceNames.length; i++) { resources[i] = new ClassPathResource(resourceNames[i], relativeClass); } this.reader.loadBeanDefinitions(resources); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\XmlServletWebServerApplicationContext.java
1
请完成以下Java代码
protected void startProcessDefinitionByKey(Job job, String configuration, DeploymentManager deploymentManager, CommandContext commandContext) { // it says getActivityId, but < 5.21, this would have the process definition key stored String processDefinitionKey = TimerEventHandler.getActivityIdFromConfiguration(configuration); ProcessDefinition processDefinition = null; if (job.getTenantId() == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(job.getTenantId())) { processDefinition = deploymentManager.findDeployedLatestProcessDefinitionByKey(processDefinitionKey); } else { processDefinition = deploymentManager.findDeployedLatestProcessDefinitionByKeyAndTenantId(processDefinitionKey, job.getTenantId()); } if (processDefinition == null) { throw new ActivitiException("Could not find process definition needed for timer start event"); } try { if (!deploymentManager.isProcessDefinitionSuspended(processDefinition.getId())) { dispatchTimerFiredEvent(job, commandContext); new StartProcessInstanceCmd<ProcessInstance>(processDefinitionKey, null, null, null, job.getTenantId()).execute(commandContext); } else {
LOGGER.debug("Ignoring timer of suspended process definition {}", processDefinition.getId()); } } catch (RuntimeException e) { LOGGER.error("exception during timer execution", e); throw e; } catch (Exception e) { LOGGER.error("exception during timer execution", e); throw new ActivitiException("exception during timer execution: " + e.getMessage(), e); } } protected void dispatchTimerFiredEvent(Job job, CommandContext commandContext) { if (commandContext.getEventDispatcher().isEnabled()) { commandContext.getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.TIMER_FIRED, job), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerStartEventJobHandler.java
1
请完成以下Java代码
public static StockQtyAndUOMQty toZeroIfNegative(@NonNull final StockQtyAndUOMQty stockQtyAndUOMQty) { return stockQtyAndUOMQty.signum() < 0 ? stockQtyAndUOMQty.toZero() : stockQtyAndUOMQty; } @NonNull public static StockQtyAndUOMQty toZeroIfPositive(@NonNull final StockQtyAndUOMQty stockQtyAndUOMQty) { return stockQtyAndUOMQty.signum() > 0 ? stockQtyAndUOMQty.toZero() : stockQtyAndUOMQty; } public Quantity getQtyInUOM(@NonNull final UomId uomId, @NonNull final QuantityUOMConverter converter) { if (uomQty != null) { if (UomId.equals(uomQty.getUomId(), uomId)) { return uomQty; } else if (UomId.equals(uomQty.getSourceUomId(), uomId))
{ return uomQty.switchToSource(); } } if (UomId.equals(stockQty.getUomId(), uomId)) { return stockQty; } else if (UomId.equals(stockQty.getSourceUomId(), uomId)) { return stockQty.switchToSource(); } return converter.convertQuantityTo(stockQty, productId, uomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\StockQtyAndUOMQty.java
1
请完成以下Java代码
public void addPrinterHW(final PrinterHWList printerHWList) { log.info("Found printer HWs: " + printerHWList); } public void addPrintPackage(final PrintPackage printPackage, final InputStream printDataStream) { synchronized (sync) { final String trx = printPackage.getTransactionId(); if (trx2PrintPackageMap.containsKey(trx)) { throw new IllegalArgumentException("Transaction already exists in queue: " + printPackage); } final PrintPackageAndData item = new PrintPackageAndData(); item.printPackage = printPackage; item.printDataStream = printDataStream; printPackageQueue.add(item); trx2PrintPackageMap.put(trx, item); } } @Override public PrintPackage getNextPrintPackage() { synchronized (sync) { final PrintPackageAndData item = printPackageQueue.poll(); if (item == null) { return null; } System.out.println("getNextPrintPackage: " + item.printPackage); return item.printPackage; } } @Override public InputStream getPrintPackageData(final PrintPackage printPackage) { synchronized (sync) { final String trx = printPackage.getTransactionId(); final PrintPackageAndData item = trx2PrintPackageMap.remove(trx); if (item == null) { throw new IllegalStateException("No data found for " + printPackage); }
System.out.println("getPrintPackageData: trx=" + trx + " => stream: " + item.printDataStream); return item.printDataStream; } } @Override public void sendPrintPackageResponse(final PrintPackage printPackage, final PrintJobInstructionsConfirm response) { log.info("Got : " + response + " for " + printPackage); } private static class PrintPackageAndData { public PrintPackage printPackage; public InputStream printDataStream; } @Override public LoginResponse login(final LoginRequest loginRequest) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\endpoint\BufferedPrintConnectionEndpoint.java
1
请完成以下Java代码
protected void prepare() { // nothing to prepare } @Override protected String doIt() throws Exception { final I_Fresh_QtyOnHand onHand = getProcessInfo().getRecord(I_Fresh_QtyOnHand.class); final Timestamp dateDoc = onHand.getDateDoc(); final PlainContextAware contextProviderForNewRecords = PlainContextAware.newWithTrxName(getCtx(), getTrxName()); final Iterator<I_Fresh_QtyOnHand_Line> linesWithDateDoc = retrieveLinesWithDateDoc(dateDoc); int seqNo = 0; int count = 0; for (final I_Fresh_QtyOnHand_Line qtyOnHandLine : IteratorUtils.asIterable(linesWithDateDoc)) { seqNo += SEQNO_SPACING; count++; qtyOnHandLine.setSeqNo(seqNo); InterfaceWrapperHelper.save(qtyOnHandLine); } return "@Success@: @Updated@ " + count + " @Fresh_QtyOnHand_Line@"; } private Iterator<I_Fresh_QtyOnHand_Line> retrieveLinesWithDateDoc(final Timestamp dateDoc) { final IQueryBuilder<I_Fresh_QtyOnHand_Line> linesWithDateDocQueryBuilder = queryBL.createQueryBuilder(I_Fresh_QtyOnHand.class, getCtx(), ITrx.TRXNAME_None) .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_Fresh_QtyOnHand.COLUMN_Processed, true) .addEqualsFilter(I_Fresh_QtyOnHand.COLUMN_DateDoc, dateDoc) .andCollectChildren(I_Fresh_QtyOnHand_Line.COLUMN_Fresh_QtyOnHand_ID, I_Fresh_QtyOnHand_Line.class); linesWithDateDocQueryBuilder.orderBy() .addColumn(I_Fresh_QtyOnHand_Line.COLUMNNAME_ProductGroup) .addColumn(I_Fresh_QtyOnHand_Line.COLUMNNAME_ProductName) .addColumn(I_Fresh_QtyOnHand_Line.COLUMNNAME_M_Product_ID); // note: same M_Product_ID => same Group and Name return linesWithDateDocQueryBuilder .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, false) .setOption(IQuery.OPTION_IteratorBufferSize, 1000) .iterate(I_Fresh_QtyOnHand_Line.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\freshQtyOnHand\process\Fresh_QtyOnHand_UpdateSeqNo_And_Export_SortPref.java
1
请在Spring Boot框架中完成以下Java代码
public Resource getResource() { return this.resource; } /** * Return the profile or {@code null} if the resource is not profile specific. * @return the profile or {@code null} * @since 2.4.6 */ public @Nullable String getProfile() { return this.reference.getProfile(); } boolean isEmptyDirectory() { return this.emptyDirectory; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } StandardConfigDataResource other = (StandardConfigDataResource) obj; return (this.emptyDirectory == other.emptyDirectory) && isSameUnderlyingResource(this.resource, other.resource); } private boolean isSameUnderlyingResource(Resource ours, Resource other) { return ours.equals(other) || isSameFile(getUnderlyingFile(ours), getUnderlyingFile(other)); } private boolean isSameFile(@Nullable File ours, @Nullable File other) { return (ours != null) && ours.equals(other); }
@Override public int hashCode() { File underlyingFile = getUnderlyingFile(this.resource); return (underlyingFile != null) ? underlyingFile.hashCode() : this.resource.hashCode(); } @Override public String toString() { if (this.resource instanceof FileSystemResource || this.resource instanceof FileUrlResource) { try { return "file [" + this.resource.getFile() + "]"; } catch (IOException ex) { // Ignore } } return this.resource.toString(); } private @Nullable File getUnderlyingFile(Resource resource) { try { if (resource instanceof ClassPathResource || resource instanceof FileSystemResource || resource instanceof FileUrlResource) { return resource.getFile().getAbsoluteFile(); } } catch (IOException ex) { // Ignore } return null; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\StandardConfigDataResource.java
2
请完成以下Java代码
public class SubProcessParseHandler extends AbstractActivityBpmnParseHandler<SubProcess> { @Override protected Class<? extends BaseElement> getHandledType() { return SubProcess.class; } @Override protected void executeParse(BpmnParse bpmnParse, SubProcess subProcess) { ActivityImpl activity = createActivityOnScope(bpmnParse, subProcess, BpmnXMLConstants.ELEMENT_SUBPROCESS, bpmnParse.getCurrentScope()); activity.setAsync(subProcess.isAsynchronous()); activity.setExclusive(!subProcess.isNotExclusive()); boolean triggeredByEvent = false; if (subProcess instanceof EventSubProcess) { triggeredByEvent = true; } activity.setProperty("triggeredByEvent", triggeredByEvent); // event subprocesses are not scopes activity.setScope(!triggeredByEvent); activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createSubprocActivityBehavior(subProcess)); bpmnParse.setCurrentScope(activity); bpmnParse.setCurrentSubProcess(subProcess);
bpmnParse.processFlowElements(subProcess.getFlowElements()); processArtifacts(bpmnParse, subProcess.getArtifacts(), activity); // no data objects for event subprocesses if (!(subProcess instanceof EventSubProcess)) { // parse out any data objects from the template in order to set up the necessary process variables Map<String, Object> variables = processDataObjects(bpmnParse, subProcess.getDataObjects(), activity); activity.setVariables(variables); } bpmnParse.removeCurrentScope(); bpmnParse.removeCurrentSubProcess(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SubProcessParseHandler.java
1
请完成以下Java代码
public void setAD_PrintFormat(final org.compiere.model.I_AD_PrintFormat AD_PrintFormat) { set_ValueFromPO(COLUMNNAME_AD_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class, AD_PrintFormat); } @Override public void setAD_PrintFormat_ID (final int AD_PrintFormat_ID) { if (AD_PrintFormat_ID < 1) set_Value (COLUMNNAME_AD_PrintFormat_ID, null); else set_Value (COLUMNNAME_AD_PrintFormat_ID, AD_PrintFormat_ID); } @Override public int getAD_PrintFormat_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrintFormat_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); }
@Override public void setM_Product_PrintFormat_ID (final int M_Product_PrintFormat_ID) { if (M_Product_PrintFormat_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_PrintFormat_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_PrintFormat_ID, M_Product_PrintFormat_ID); } @Override public int getM_Product_PrintFormat_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_PrintFormat_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_PrintFormat.java
1
请完成以下Java代码
private CostSegmentAndElementBuilder extractCommonCostSegmentAndElement(final MoveCostsRequest request) { final AcctSchema acctSchema = getAcctSchemaById(request.getAcctSchemaId()); final CostingLevel costingLevel = productCostingBL.getCostingLevel(request.getProductId(), acctSchema); final CostTypeId costTypeId = acctSchema.getCosting().getCostTypeId(); return CostSegmentAndElement.builder() .costingLevel(costingLevel) .acctSchemaId(request.getAcctSchemaId()) .costTypeId(costTypeId) .clientId(request.getClientId()) // .orgId(null) // to be set by caller .productId(request.getProductId()) .attributeSetInstanceId(request.getAttributeSetInstanceId()) .costElementId(request.getCostElementId()); } @Override public void delete(final CostDetail costDetail)
{ costDetailsRepo.delete(costDetail); } @Override public Stream<CostDetail> stream(@NonNull final CostDetailQuery query) { return costDetailsRepo.stream(query); } @Override public Optional<CostDetail> firstOnly(@NonNull final CostDetailQuery query) { return costDetailsRepo.firstOnly(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CostDetailService.java
1
请完成以下Java代码
public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Line No. @return Unique line for this document */ public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Shipment/Receipt Line. @param M_InOutLine_ID Line on Shipment or Receipt document */ public void setM_InOutLine_ID (int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_Value (COLUMNNAME_M_InOutLine_ID, null); else set_Value (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID)); } /** Get Shipment/Receipt Line. @return Line on Shipment or Receipt document */ public int getM_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Addition.java
1
请完成以下Java代码
public List<I_PMM_Message> retrieveMessages(final Properties ctx) { return Services.get(IQueryBL.class) .createQueryBuilder(I_PMM_Message.class, ctx, ITrx.TRXNAME_ThreadInherited) .addOnlyActiveRecordsFilter() // .orderBy() .addColumn(I_PMM_Message.COLUMNNAME_PMM_Message_ID) .endOrderBy() // .create() .list(); } @Override public String retrieveMessagesAsString(final Properties ctx) { final StringBuilder messages = new StringBuilder(); for (final I_PMM_Message pmmMessage : retrieveMessages(ctx)) {
final String message = pmmMessage.getMsgText(); if (Check.isEmpty(message, true)) { continue; } if (messages.length() > 0) { messages.append("\n"); } messages.append(message.trim()); } return messages.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMMMessageDAO.java
1
请完成以下Java代码
public void configureCaches(String contextParameter) { HalRelationCacheConfiguration configuration = new HalRelationCacheConfiguration(contextParameter); configureCaches(configuration); } public void configureCaches(HalRelationCacheConfiguration configuration) { Class<? extends Cache> cacheClass = configuration.getCacheImplementationClass(); for (Map.Entry<Class<?>, Map<String, Object>> cacheConfiguration : configuration.getCacheConfigurations().entrySet()) { Cache cache = createCache(cacheClass, cacheConfiguration.getValue()); registerCache(cacheConfiguration.getKey(), cache); } } protected Cache createCache(Class<? extends Cache> cacheClass, Map<String, Object> cacheConfiguration) { Cache cache = createCacheInstance(cacheClass); configureCache(cache, cacheConfiguration); return cache; } protected void configureCache(Cache cache, Map<String, Object> cacheConfiguration) { for (Map.Entry<String, Object> configuration : cacheConfiguration.entrySet()) { configureCache(cache, configuration.getKey(), configuration.getValue()); } } protected Cache createCacheInstance(Class<? extends Cache> cacheClass) { try { return ReflectUtil.instantiate(cacheClass); } catch (ProcessEngineException e) { throw new HalRelationCacheConfigurationException("Unable to instantiate cache class " + cacheClass.getName(), e); } } protected void configureCache(Cache cache, String property, Object value) { Method setter; try { setter = ReflectUtil.getSingleSetter(property, cache.getClass()); }
catch (ProcessEngineException e) { throw new HalRelationCacheConfigurationException("Unable to find setter for property " + property, e); } if (setter == null) { throw new HalRelationCacheConfigurationException("Unable to find setter for property " + property); } try { setter.invoke(cache, value); } catch (IllegalAccessException e) { throw new HalRelationCacheConfigurationException("Unable to access setter for property " + property); } catch (InvocationTargetException e) { throw new HalRelationCacheConfigurationException("Unable to invoke setter for property " + property); } } protected void registerCache(Class<?> halResourceClass, Cache cache) { Hal.getInstance().registerHalRelationCache(halResourceClass, cache); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\HalRelationCacheBootstrap.java
1
请完成以下Java代码
public boolean isCompletable() { return completable; } public boolean isOnlyStages() { return onlyStages; } public String getEntryCriterionId() { return entryCriterionId; } public String getExitCriterionId() { return exitCriterionId; } public String getFormKey() { return formKey; } public String getExtraValue() { return extraValue; } public String getInvolvedUser() { return involvedUser; } public Collection<String> getInvolvedGroups() { return involvedGroups; } public String getTenantId() { return tenantId; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isIncludeLocalVariables() { return includeLocalVariables;
} public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } @Override protected void ensureVariablesInitialized() { super.ensureVariablesInitialized(); for (PlanItemInstanceQueryImpl orQueryObject : orQueryObjects) { orQueryObject.ensureVariablesInitialized(); } } public List<PlanItemInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeCaseInstanceIds = safeProcessInstanceIds; } public Collection<String> getCaseInstanceIds() { return caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\PlanItemInstanceQueryImpl.java
1
请完成以下Java代码
public final class JerseyHealthEndpointAdditionalPathResourceFactory { private final JerseyEndpointResourceFactory delegate = new JerseyEndpointResourceFactory(); private final Set<HealthEndpointGroup> groups; private final WebServerNamespace serverNamespace; public JerseyHealthEndpointAdditionalPathResourceFactory(WebServerNamespace serverNamespace, HealthEndpointGroups groups) { this.serverNamespace = serverNamespace; this.groups = groups.getAllWithAdditionalPath(serverNamespace); } public Collection<Resource> createEndpointResources(EndpointMapping endpointMapping, Collection<ExposableWebEndpoint> endpoints) { return endpoints.stream() .flatMap((endpoint) -> endpoint.getOperations().stream()) .flatMap((operation) -> createResources(endpointMapping, operation)) .toList(); } private Stream<Resource> createResources(EndpointMapping endpointMapping, WebOperation operation) { WebOperationRequestPredicate requestPredicate = operation.getRequestPredicate(); String matchAllRemainingPathSegmentsVariable = requestPredicate.getMatchAllRemainingPathSegmentsVariable();
if (matchAllRemainingPathSegmentsVariable != null) { List<Resource> resources = new ArrayList<>(); for (HealthEndpointGroup group : this.groups) { AdditionalHealthEndpointPath additionalPath = group.getAdditionalPath(); if (additionalPath != null) { resources.add(this.delegate.getResource(endpointMapping, operation, requestPredicate, additionalPath.getValue(), this.serverNamespace, (data, pathSegmentsVariable) -> data.getUriInfo().getPath())); } } return resources.stream(); } return Stream.empty(); } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\actuate\endpoint\web\JerseyHealthEndpointAdditionalPathResourceFactory.java
1
请完成以下Java代码
public void setM_PricingSystem_ID (int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, Integer.valueOf(M_PricingSystem_ID)); } /** Get Preissystem. @return Ein Preissystem enthält beliebig viele, Länder-abhängige Preislisten. */ @Override public int getM_PricingSystem_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PricingSystem_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () {
return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Preis Präzision. @param PricePrecision Precision (number of decimals) for the Price */ @Override public void setPricePrecision (int PricePrecision) { set_Value (COLUMNNAME_PricePrecision, Integer.valueOf(PricePrecision)); } /** Get Preis Präzision. @return Precision (number of decimals) for the Price */ @Override public int getPricePrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_PricePrecision); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList.java
1
请完成以下Java代码
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumerische Bezeichnung fuer diesen Eintrag */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumerische Bezeichnung fuer diesen Eintrag */ 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 Suchschluessel. @param Value Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschluessel. @return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ 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\adempiere\model\X_M_FreightCost.java
1
请完成以下Java代码
public class HttpExchangesFilter extends OncePerRequestFilter implements Ordered { // Not LOWEST_PRECEDENCE, but near the end, so it has a good chance of catching all // enriched headers, but users can add stuff after this if they want to private int order = Ordered.LOWEST_PRECEDENCE - 10; private final HttpExchangeRepository repository; private final Set<Include> includes; /** * Create a new {@link HttpExchangesFilter} instance. * @param repository the repository used to record events * @param includes the include options */ public HttpExchangesFilter(HttpExchangeRepository repository, Set<Include> includes) { this.repository = repository; this.includes = includes; } @Override public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!isRequestValid(request)) { filterChain.doFilter(request, response); return; } RecordableServletHttpRequest sourceRequest = new RecordableServletHttpRequest(request); HttpExchange.Started startedHttpExchange = HttpExchange.start(sourceRequest); int status = HttpStatus.INTERNAL_SERVER_ERROR.value(); try {
filterChain.doFilter(request, response); status = response.getStatus(); } finally { RecordableServletHttpResponse sourceResponse = new RecordableServletHttpResponse(response, status); HttpExchange finishedExchange = startedHttpExchange.finish(sourceResponse, request::getUserPrincipal, () -> getSessionId(request), this.includes); this.repository.add(finishedExchange); } } private boolean isRequestValid(HttpServletRequest request) { try { new URI(request.getRequestURL().toString()); return true; } catch (URISyntaxException ex) { return false; } } private @Nullable String getSessionId(HttpServletRequest request) { HttpSession session = request.getSession(false); return (session != null) ? session.getId() : null; } }
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\actuate\web\exchanges\HttpExchangesFilter.java
1
请在Spring Boot框架中完成以下Java代码
protected AiModel prepare( EntitiesImportCtx ctx, AiModel model, AiModel oldModel, EntityExportData<AiModel> exportData, BaseEntityImportService<AiModelId, AiModel, EntityExportData<AiModel>>.IdProvider idProvider ) { return model; } @Override protected AiModel deepCopy(AiModel model) { return new AiModel(model); } @Override
protected AiModel saveOrUpdate( EntitiesImportCtx ctx, AiModel model, EntityExportData<AiModel> exportData, BaseEntityImportService<AiModelId, AiModel, EntityExportData<AiModel>>.IdProvider idProvider, CompareResult compareResult ) { return aiModelService.save(model); } @Override public EntityType getEntityType() { return EntityType.AI_MODEL; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\AiModelImportService.java
2
请完成以下Java代码
public class OrderBillLocationAdapter implements IDocumentBillLocationAdapter, RecordBasedLocationAdapter<OrderBillLocationAdapter> { private final I_C_Order delegate; OrderBillLocationAdapter(@NonNull final I_C_Order delegate) { this.delegate = delegate; } @Override public int getBill_BPartner_ID() { return delegate.getBill_BPartner_ID(); } @Override public void setBill_BPartner_ID(final int Bill_BPartner_ID) { delegate.setBill_BPartner_ID(Bill_BPartner_ID); } @Override public int getBill_Location_ID() { return delegate.getBill_Location_ID(); } @Override public void setBill_Location_ID(final int Bill_Location_ID) { delegate.setBill_Location_ID(Bill_Location_ID); } @Override public int getBill_Location_Value_ID() { return delegate.getBill_Location_Value_ID(); } @Override public void setBill_Location_Value_ID(final int Bill_Location_Value_ID) { delegate.setBill_Location_Value_ID(Bill_Location_Value_ID); } @Override public int getBill_User_ID() { return delegate.getBill_User_ID(); } @Override public void setBill_User_ID(final int Bill_User_ID) { delegate.setBill_User_ID(Bill_User_ID);
} @Override public String getBillToAddress() { return delegate.getBillToAddress(); } @Override public void setBillToAddress(final String address) { delegate.setBillToAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddress(from); } public void setFromBillLocation(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.billLocationAdapter(from).toDocumentLocation()); } @Override public I_C_Order getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public OrderBillLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new OrderBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderBillLocationAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public final String getcInvoiceID() { return cInvoiceID; } public final void setcInvoiceID(final String cInvoiceID) { this.cInvoiceID = cInvoiceID; } public String getDiscount() { return discount; } public void setDiscount(final String discount) { this.discount = discount; } public Date getDiscountDate() { return discountDate; } public void setDiscountDate(final Date discountDate) { this.discountDate = discountDate; } public String getDiscountDays() { return discountDays; } public void setDiscountDays(final String discountDays) { this.discountDays = discountDays; } public String getRate() { return rate; } public void setRate(final String rate) { this.rate = rate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (cInvoiceID == null ? 0 : cInvoiceID.hashCode()); result = prime * result + (discount == null ? 0 : discount.hashCode()); result = prime * result + (discountDate == null ? 0 : discountDate.hashCode()); result = prime * result + (discountDays == null ? 0 : discountDays.hashCode()); result = prime * result + (rate == null ? 0 : rate.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cctop140V other = (Cctop140V)obj; if (cInvoiceID == null) { if (other.cInvoiceID != null) { return false; } } else if (!cInvoiceID.equals(other.cInvoiceID)) { return false; } if (discount == null) { if (other.discount != null) { return false; } } else if (!discount.equals(other.discount)) {
return false; } if (discountDate == null) { if (other.discountDate != null) { return false; } } else if (!discountDate.equals(other.discountDate)) { return false; } if (discountDays == null) { if (other.discountDays != null) { return false; } } else if (!discountDays.equals(other.discountDays)) { return false; } if (rate == null) { if (other.rate != null) { return false; } } else if (!rate.equals(other.rate)) { return false; } return true; } @Override public String toString() { return "Cctop140V [cInvoiceID=" + cInvoiceID + ", discount=" + discount + ", discountDate=" + discountDate + ", discountDays=" + discountDays + ", rate=" + rate + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop140V.java
2
请完成以下Java代码
public class Vector { float[] elementArray; public Vector(float[] elementArray) { this.elementArray = elementArray; } public Vector(int size) { elementArray = new float[size]; Arrays.fill(elementArray, 0); } public int size() { return elementArray.length; } public float dot(Vector other) { float ret = 0.0f; for (int i = 0; i < size(); ++i) { ret += elementArray[i] * other.elementArray[i]; } return ret; } public float norm() { float ret = 0.0f; for (int i = 0; i < size(); ++i) { ret += elementArray[i] * elementArray[i]; } return (float) Math.sqrt(ret); } /** * 夹角的余弦<br> * 认为this和other都是单位向量,所以方法内部没有除以两者的模。 * * @param other * @return */ public float cosineForUnitVector(Vector other) { return dot(other); } /** * 夹角的余弦<br> * * @param other * @return */ public float cosine(Vector other) { return dot(other) / this.norm() / other.norm(); } public Vector minus(Vector other) { float[] result = new float[size()]; for (int i = 0; i < result.length; i++) { result[i] = elementArray[i] - other.elementArray[i]; } return new Vector(result); } public Vector add(Vector other) { float[] result = new float[size()];
for (int i = 0; i < result.length; i++) { result[i] = elementArray[i] + other.elementArray[i]; } return new Vector(result); } public Vector addToSelf(Vector other) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] + other.elementArray[i]; } return this; } public Vector divideToSelf(int n) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] / n; } return this; } public Vector divideToSelf(float f) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] / f; } return this; } /** * 自身归一化 * * @return */ public Vector normalize() { divideToSelf(norm()); return this; } public float[] getElementArray() { return elementArray; } public void setElementArray(float[] elementArray) { this.elementArray = elementArray; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Vector.java
1
请完成以下Java代码
public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; }
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ManyToOne @JoinColumn(name = "customer_id") private User customer; }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\Product.java
1
请完成以下Java代码
public void nullSafeSet(PreparedStatement st, String[] value, int index, SharedSessionContractImplementor session) throws SQLException { if (st != null) { if (value != null) { Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("text", value); st.setArray(index, array); } else { st.setNull(index, Types.ARRAY); } } } @Override public String[] deepCopy(String[] value) { return value != null ? Arrays.copyOf(value, value.length) : null; } @Override public boolean isMutable() { return false; }
@Override public Serializable disassemble(String[] value) { return value; } @Override public String[] assemble(Serializable cached, Object owner) { return (String[]) cached; } @Override public String[] replace(String[] detached, String[] managed, Object owner) { return detached; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\arraymapping\CustomStringArrayType.java
1
请完成以下Java代码
private static AttributesIncludedTabDataField writeValueAsInteger(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField) { return dataField.withNumberValue(documentField.getValueAs(Integer.class)); } private static AttributesIncludedTabDataField writeValueAsBigDecimal(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField) { return dataField.withNumberValue(documentField.getValueAs(BigDecimal.class)); } private static AttributesIncludedTabDataField writeValueAsString(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField) { return dataField.withStringValue(documentField.getValueAs(String.class)); } private static AttributesIncludedTabDataField writeValueAsListItem(final AttributesIncludedTabDataField dataField, final IDocumentFieldView documentField) { final StringLookupValue lookupValue = documentField.getValueAs(StringLookupValue.class); final String valueString = lookupValue != null ? lookupValue.getIdAsString() : null; final AttributeValueId valueItemId = documentField.getDescriptor().getLookupDescriptor().get().cast(ASILookupDescriptor.class).getAttributeValueId(valueString); return dataField.withListValue(valueString, valueItemId); } public Object getValue(final @NonNull AttributesIncludedTabData data) { return valueReader.readValue(data, attributeId); }
public AttributesIncludedTabDataField updateData(final @NonNull AttributesIncludedTabDataField dataField, final IDocumentFieldView documentField) { return valueWriter.writeValue(dataField, documentField); } // // // // // @FunctionalInterface private interface ValueReader { Object readValue(AttributesIncludedTabData data, AttributeId attributeId); } @FunctionalInterface private interface ValueWriter { AttributesIncludedTabDataField writeValue(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabFieldBinding.java
1
请完成以下Java代码
public Object getValue(final String columnName, final int idx, final Class<?> returnType) { return POWrapper.this.getValue(columnName, idx, returnType); } @Override public Object getValue(final String columnName, final Class<?> returnType) { final int columnIndex = POWrapper.this.getColumnIndex(columnName); return POWrapper.this.getValue(columnName, columnIndex, returnType); } @Override public Object getReferencedObject(final String columnName, final Method interfaceMethod) throws Exception { return POWrapper.this.getReferencedObject(columnName, interfaceMethod); } @Override public Set<String> getColumnNames() { return POWrapper.this.getColumnNames(); } @Override public int getColumnIndex(final String columnName) { return POWrapper.this.getColumnIndex(columnName); }
@Override public boolean isVirtualColumn(final String columnName) { return POWrapper.this.isVirtualColumn(columnName); } @Override public boolean isKeyColumnName(final String columnName) { return POWrapper.this.isKeyColumnName(columnName); } ; @Override public boolean isCalculated(final String columnName) { return POWrapper.this.isCalculated(columnName); } @Override public boolean hasColumnName(final String columnName) { return POWrapper.this.hasColumnName(columnName); } }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\POWrapper.java
1
请完成以下Java代码
public void setDischargeDate (final @Nullable java.sql.Timestamp DischargeDate) { set_Value (COLUMNNAME_DischargeDate, DischargeDate); } @Override public java.sql.Timestamp getDischargeDate() { return get_ValueAsTimestamp(COLUMNNAME_DischargeDate); } @Override public void setIsIVTherapy (final boolean IsIVTherapy) { set_Value (COLUMNNAME_IsIVTherapy, IsIVTherapy); } @Override public boolean isIVTherapy() { return get_ValueAsBoolean(COLUMNNAME_IsIVTherapy); } @Override public void setIsTransferPatient (final boolean IsTransferPatient) { set_Value (COLUMNNAME_IsTransferPatient, IsTransferPatient); } @Override public boolean isTransferPatient() { return get_ValueAsBoolean(COLUMNNAME_IsTransferPatient); } @Override public void setNumberOfInsured (final @Nullable String NumberOfInsured) { set_Value (COLUMNNAME_NumberOfInsured, NumberOfInsured); } @Override public String getNumberOfInsured() { return get_ValueAsString(COLUMNNAME_NumberOfInsured); } /** * PayerType AD_Reference_ID=541319 * Reference name: PayerType_list */ public static final int PAYERTYPE_AD_Reference_ID=541319; /** Unbekannt = 0 */
public static final String PAYERTYPE_Unbekannt = "0"; /** Gesetzlich = 1 */ public static final String PAYERTYPE_Gesetzlich = "1"; /** Privat = 2 */ public static final String PAYERTYPE_Privat = "2"; /** Berufsgenossenschaft = 3 */ public static final String PAYERTYPE_Berufsgenossenschaft = "3"; /** Selbstzahler = 4 */ public static final String PAYERTYPE_Selbstzahler = "4"; /** Andere = 5 */ public static final String PAYERTYPE_Andere = "5"; @Override public void setPayerType (final @Nullable String PayerType) { set_Value (COLUMNNAME_PayerType, PayerType); } @Override public String getPayerType() { return get_ValueAsString(COLUMNNAME_PayerType); } @Override public void setUpdatedAt (final @Nullable java.sql.Timestamp UpdatedAt) { set_Value (COLUMNNAME_UpdatedAt, UpdatedAt); } @Override public java.sql.Timestamp getUpdatedAt() { return get_ValueAsTimestamp(COLUMNNAME_UpdatedAt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_AlbertaPatient.java
1
请完成以下Java代码
public class StageXmlConverter extends PlanItemDefinitionXmlConverter { @Override public String getXMLElementName() { return CmmnXmlConstants.ELEMENT_STAGE; } @Override public boolean hasChildElements() { return true; } @Override protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { Stage stage = new Stage(); stage.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME)); stage.setAutoComplete(Boolean.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_IS_AUTO_COMPLETE))); stage.setAutoCompleteCondition(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_AUTO_COMPLETE_CONDITION)); String displayOrderString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_DISPLAY_ORDER); if (StringUtils.isNotEmpty(displayOrderString)) { stage.setDisplayOrder(Integer.valueOf(displayOrderString)); } String includeInStageOverviewString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_INCLUDE_IN_STAGE_OVERVIEW); if (StringUtils.isNotEmpty(includeInStageOverviewString)) { stage.setIncludeInStageOverview(includeInStageOverviewString);
} else { stage.setIncludeInStageOverview("true"); // True by default } stage.setCase(conversionHelper.getCurrentCase()); stage.setParent(conversionHelper.getCurrentPlanFragment()); conversionHelper.setCurrentStage(stage); conversionHelper.addStage(stage); String businessStatus = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_BUSINESS_STATUS); if (StringUtils.isNotEmpty(businessStatus)) { stage.setBusinessStatus(businessStatus); } return stage; } @Override protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) { super.elementEnd(xtr, conversionHelper); conversionHelper.removeCurrentStage(); } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\StageXmlConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class LocationId implements RepoIdAware { @JsonCreator public static LocationId ofRepoId(final int repoId) { return new LocationId(repoId); } @Nullable public static LocationId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } int repoId; private LocationId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Location_ID"); } public static int toRepoId(@Nullable final LocationId locationId) { return toRepoIdOr(locationId, -1); }
public static int toRepoIdOr(@Nullable final LocationId locationId, final int defaultValue) { return locationId != null ? locationId.getRepoId() : defaultValue; } @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final LocationId id1, @Nullable final LocationId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\LocationId.java
2
请完成以下Java代码
public java.lang.String getTitle () { return (java.lang.String)get_Value(COLUMNNAME_Title); } /** Set Offener Saldo. @param TotalOpenBalance Gesamt der offenen Beträge in primärer Buchführungswährung */ @Override public void setTotalOpenBalance (final BigDecimal TotalOpenBalance) { set_Value (COLUMNNAME_TotalOpenBalance, TotalOpenBalance); } /** Get Offener Saldo. @return Gesamt der offenen Beträge in primärer Buchführungswährung */ @Override public BigDecimal getTotalOpenBalance () { final BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalOpenBalance); if (bd == null) { return BigDecimal.ZERO; } return bd; } /** Set V_BPartnerCockpit_ID. @param V_BPartnerCockpit_ID V_BPartnerCockpit_ID */ @Override public void setV_BPartnerCockpit_ID (final int V_BPartnerCockpit_ID) { if (V_BPartnerCockpit_ID < 1) { set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, null); } else { set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, Integer.valueOf(V_BPartnerCockpit_ID)); } } /** Get V_BPartnerCockpit_ID. @return V_BPartnerCockpit_ID */ @Override
public int getV_BPartnerCockpit_ID () { final Integer ii = (Integer)get_Value(COLUMNNAME_V_BPartnerCockpit_ID); if (ii == null) { return 0; } return ii.intValue(); } /** Set Suchschlüssel. @param value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setvalue (final java.lang.String value) { set_Value (COLUMNNAME_value, value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getvalue () { return (java.lang.String)get_Value(COLUMNNAME_value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_V_BPartnerCockpit.java
1
请完成以下Java代码
public void update(T model) { mapper.updateByPrimaryKeySelective(model); } public T findById(Integer id) { return mapper.selectByPrimaryKey(id); } @Override public T findBy(String fieldName, Object value) throws TooManyResultsException { try { T model = modelClass.newInstance(); Field field = modelClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(model, value); return mapper.selectOne(model); } catch (ReflectiveOperationException e) { throw new ServiceException(e.getMessage(), e);
} } public List<T> findByIds(String ids) { return mapper.selectByIds(ids); } public List<T> findByCondition(Condition condition) { return mapper.selectByCondition(condition); } public List<T> findAll() { return mapper.selectAll(); } }
repos\spring-boot-api-project-seed-master\src\main\java\com\company\project\core\AbstractService.java
1
请完成以下Java代码
public String toString() { return "ProductionMaterialQuery [types=" + types + ", product=" + product + ", ppOrder=" + ppOrder + "]"; } @Override public IProductionMaterialQuery setTypes(final ProductionMaterialType... types) { if (types == null || types.length == 0) { this.types = null; } else { this.types = Arrays.asList(types); } return this; } @Override public List<ProductionMaterialType> getTypes() { if (types == null) { return Collections.emptyList(); } return types; } @Override
public IProductionMaterialQuery setM_Product(final I_M_Product product) { this.product = product; return this; } @Override public I_M_Product getM_Product() { return product; } @Override public IProductionMaterialQuery setPP_Order(final I_PP_Order ppOrder) { this.ppOrder = ppOrder; return this; } @Override public I_PP_Order getPP_Order() { return ppOrder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\ProductionMaterialQuery.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProvinceId() { return provinceId; } public void setProvinceId(Long provinceId) { this.provinceId = provinceId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; }
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "City{" + "id=" + id + ", provinceId=" + provinceId + ", cityName='" + cityName + '\'' + ", description='" + description + '\'' + '}'; } }
repos\springboot-learning-example-master\springboot-dubbo-client\src\main\java\org\spring\springboot\domain\City.java
1
请完成以下Java代码
public List<String> getTenantIdIn() { return tenantIdIn; } public void setTenantIdIn(List<String> tenantIdIn) { this.tenantIdIn = tenantIdIn; } public boolean isIncludeExtensionProperties() { return includeExtensionProperties; } public void setIncludeExtensionProperties(boolean includeExtensionProperties) { this.includeExtensionProperties = includeExtensionProperties; } public static TopicRequestDto fromTopicSubscription(TopicSubscription topicSubscription, long clientLockDuration) { Long lockDuration = topicSubscription.getLockDuration(); if (lockDuration == null) { lockDuration = clientLockDuration; } String topicName = topicSubscription.getTopicName(); List<String> variables = topicSubscription.getVariableNames(); String businessKey = topicSubscription.getBusinessKey(); TopicRequestDto topicRequestDto = new TopicRequestDto(topicName, lockDuration, variables, businessKey); if (topicSubscription.getProcessDefinitionId() != null) { topicRequestDto.setProcessDefinitionId(topicSubscription.getProcessDefinitionId()); } if (topicSubscription.getProcessDefinitionIdIn() != null) { topicRequestDto.setProcessDefinitionIdIn(topicSubscription.getProcessDefinitionIdIn());
} if (topicSubscription.getProcessDefinitionKey() != null) { topicRequestDto.setProcessDefinitionKey(topicSubscription.getProcessDefinitionKey()); } if (topicSubscription.getProcessDefinitionKeyIn() != null) { topicRequestDto.setProcessDefinitionKeyIn(topicSubscription.getProcessDefinitionKeyIn()); } if (topicSubscription.isWithoutTenantId()) { topicRequestDto.setWithoutTenantId(topicSubscription.isWithoutTenantId()); } if (topicSubscription.getTenantIdIn() != null) { topicRequestDto.setTenantIdIn(topicSubscription.getTenantIdIn()); } if(topicSubscription.getProcessDefinitionVersionTag() != null) { topicRequestDto.setProcessDefinitionVersionTag(topicSubscription.getProcessDefinitionVersionTag()); } if (topicSubscription.getProcessVariables() != null) { topicRequestDto.setProcessVariables(topicSubscription.getProcessVariables()); } if (topicSubscription.isLocalVariables()) { topicRequestDto.setLocalVariables(topicSubscription.isLocalVariables()); } if(topicSubscription.isIncludeExtensionProperties()) { topicRequestDto.setIncludeExtensionProperties(topicSubscription.isIncludeExtensionProperties()); } return topicRequestDto; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\dto\TopicRequestDto.java
1
请在Spring Boot框架中完成以下Java代码
public class ReactiveRedisProjectApplication { public static void main(String[] args) { SpringApplication.run(ReactiveRedisProjectApplication.class, args); } @Bean ApplicationRunner geography(ReactiveRedisTemplate <String, String> template){ return args -> { var sicily = "Sicily"; var geoTemplate = template.opsForGeo(); var mapOfPoints = Map.of( "Arigento", new Point(13.3619389, 38.11555556), "Catania", new Point(15.0876269, 37.502669), "Palermo", new Point(13.5833333, 37.316667)); Flux.fromIterable(mapOfPoints.entrySet()) .flatMap(e -> geoTemplate.add(sicily, e.getValue(), e.getKey())) .thenMany(geoTemplate.radius(sicily, new Circle( new Point(13.583333, 37.31667), new Distance(10, RedisGeoCommands.DistanceUnit.KILOMETERS) )))
.map(GeoResult::getContent) .map(RedisGeoCommands.GeoLocation::getName) .doOnNext(System.out::println) .subscribe(); }; } @Bean ApplicationRunner list (ReactiveRedisTemplate <String, String> template) { // return args -> { var listTemplate = template.opsForList(); var listName = "spring-team"; var push = listTemplate.leftPushAll(listName, "Madhura", "Stephana", "Dr.Syer", "Yuxin", "Olga", "Violetta"); push .thenMany(listTemplate.leftPop(listName)) .doOnNext(System.out::println) .thenMany(listTemplate.leftPop(listName)) .doOnNext(System.out::println) .subscribe(); }; } }
repos\SpringBoot-Projects-FullStack-master\Part-9.1. SpringReactive-Redis-Projects\Project-1 SpringReactiveRedis\ReactiveRedisProject\src\main\java\uz\reactiveredis\pro\reactiveredisproject\ReactiveRedisProjectApplication.java
2
请完成以下Java代码
public final class MobileApplicationsMap { @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public static MobileApplicationsMap of(@NonNull final Optional<List<MobileApplication>> optionalMobileApplications) { final List<MobileApplication> applications = optionalMobileApplications.orElseGet(ImmutableList::of); return !applications.isEmpty() ? new MobileApplicationsMap(applications) : EMPTY; } private static final MobileApplicationsMap EMPTY = new MobileApplicationsMap(ImmutableList.of()); private final ImmutableList<MobileApplication> applications; private final ImmutableMap<MobileApplicationId, MobileApplication> applicationsById; private MobileApplicationsMap(@NonNull final List<MobileApplication> applications) { this.applications = ImmutableList.copyOf(applications); this.applicationsById = Maps.uniqueIndex(applications, MobileApplication::getApplicationId); }
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("applications", applications) .toString(); } public Stream<MobileApplication> stream() {return applications.stream();} public MobileApplication getById(@NonNull final MobileApplicationId id) { final MobileApplication application = applicationsById.get(id); if (application == null) { throw new AdempiereException("No registered application found for `" + id + "`. Available registered applications are: " + applicationsById.keySet()); } return application; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\mobile\application\MobileApplicationsMap.java
1
请在Spring Boot框架中完成以下Java代码
public Quantity computeQtyOfComponentsRequired( @NonNull final ProductId componentId, @NonNull final QuantityUOMConverter uomConverter) { final QtyCalculationsBOMLine bomLine = sparePartsBOM.getLineByComponentId(componentId).orElse(null); if (bomLine == null) { return null; } final Quantity qtyInBomUOM = uomConverter.convertQuantityTo(qty, bomLine.getBomProductId(), bomLine.getBomProductUOMId()); return bomLine.computeQtyRequired(qtyInBomUOM); } public ProductId getProductId() { return sparePartsBOM.getBomProductId(); }
} @Value @Builder public static class SparePart { @NonNull ProductId sparePartId; @NonNull Quantity qty; @NonNull InOutAndLineId customerReturnLineId; @NonNull HuId sparePartsVhuId; public Quantity getQty(@NonNull final UomId targetUomId, @NonNull final QuantityUOMConverter uomConverter) { return uomConverter.convertQuantityTo(getQty(), getSparePartId(), targetUomId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\customerreturns\SparePartsReturnCalculation.java
2
请完成以下Java代码
public BigDecimal getESR_Trx_Qty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Trx_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setHash (final @Nullable java.lang.String Hash) { set_Value (COLUMNNAME_Hash, Hash); } @Override public java.lang.String getHash() { return get_ValueAsString(COLUMNNAME_Hash); } @Override public void setIsArchiveFile (final boolean IsArchiveFile) { set_Value (COLUMNNAME_IsArchiveFile, IsArchiveFile); } @Override public boolean isArchiveFile() { return get_ValueAsBoolean(COLUMNNAME_IsArchiveFile); } @Override public void setIsReceipt (final boolean IsReceipt) { set_Value (COLUMNNAME_IsReceipt, IsReceipt); } @Override public boolean isReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsReceipt); } @Override public void setIsReconciled (final boolean IsReconciled) { set_Value (COLUMNNAME_IsReconciled, IsReconciled); } @Override public boolean isReconciled() { return get_ValueAsBoolean(COLUMNNAME_IsReconciled); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override
public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { throw new IllegalArgumentException ("Processing is virtual column"); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java
1
请完成以下Java代码
String concatenateOnlyIfSecondArgumentIsNotNull(String head, String tail) { if (tail == null) { return null; } if (head == null) { return tail; } return head + tail; } void uselessNullCheck() { String head = "1234"; String tail = "5678"; String concatenation = concatenateOnlyIfSecondArgumentIsNotNull(head, tail); if (concatenation != null) { System.out.println(concatenation); } } void uselessNullCheckOnInferredAnnotation() { if (StringUtils.isEmpty(null)) { System.out.println("baeldung"); } } @Contract(pure = true) String replace(String string, char oldChar, char newChar) { return string.replace(oldChar, newChar); } @Contract(value = "true -> false; false -> true", pure = true) boolean not(boolean input) { return !input; } @Contract("true -> new") void contractExpectsWrongParameterType(List<Integer> integers) { } @Contract("_, _ -> new") void contractExpectsMoreParametersThanMethodHas(String s) { } @Contract("_ -> _; null -> !null") String secondContractClauseNotReachable(String s) { return ""; } @Contract("_ -> true") void contractExpectsWrongReturnType(String s) { } // NB: the following examples demonstrate how to use the mutates attribute of the annotation // This attribute is currently experimental and could be changed or removed in the future @Contract(mutates = "param") void incrementArrayFirstElement(Integer[] integers) { if (integers.length > 0) {
integers[0] = integers[0] + 1; } } @Contract(pure = true, mutates = "param") void impossibleToMutateParamInPureFunction(List<String> strings) { if (strings != null) { strings.forEach(System.out::println); } } @Contract(mutates = "param3") void impossibleToMutateThirdParamWhenMethodHasOnlyTwoParams(int a, int b) { } @Contract(mutates = "param") void impossibleToMutableImmutableType(String s) { } @Contract(mutates = "this") static void impossibleToMutateThisInStaticMethod() { } }
repos\tutorials-master\jetbrains-annotations\src\main\java\com\baeldung\annotations\Demo.java
1
请完成以下Java代码
public class PurchaseCandidateBL implements IPurchaseCandidateBL { private final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); public void updateCandidatePricingDiscount(final PurchaseCandidate candidate) { final BPartnerId vendorId = candidate.getVendorId(); final PurchaseOrderPricingInfo pricingInfo = PurchaseOrderPricingInfo.builder() .productId(candidate.getProductId()) .orgId(candidate.getOrgId()) .quantity(candidate.getQtyToPurchase()) .bpartnerId(vendorId) .datePromised(candidate.getPurchaseDatePromised()) .countryId(bpartnerDAO.getDefaultShipToLocationCountryIdOrNull(vendorId)) .isManualPrice(candidate.isManualPrice()) .priceEntered(candidate.getPrice()) .priceEnteredUomId(candidate.getPriceUomId()) .currencyId(candidate.getCurrencyId()) .build(); final IPricingResult priceAndDiscount = getPriceAndDiscount(pricingInfo); final BigDecimal enteredPrice = candidate.isManualPrice() ? candidate.getPrice() : priceAndDiscount.getPriceStd(); final UomId enteredPriceUomId = candidate.isManualPrice() ? candidate.getPriceUomId() : priceAndDiscount.getPriceUomId(); final Percent discountPercent = candidate.isManualDiscount() ? candidate.getDiscount() : priceAndDiscount.getDiscount(); final BigDecimal priceActual = discountPercent.subtractFromBase(enteredPrice, priceAndDiscount.getPrecision().toInt());
candidate.setPrice(enteredPrice); candidate.setPriceInternal(priceAndDiscount.getPriceStd()); candidate.setPriceEnteredEff(enteredPrice); candidate.setPriceUomId(enteredPriceUomId); candidate.setDiscount(discountPercent); candidate.setDiscountInternal(priceAndDiscount.getDiscount()); candidate.setDiscountEff(discountPercent); candidate.setPriceActual(priceActual); candidate.setTaxIncluded(priceAndDiscount.isTaxIncluded()); candidate.setTaxCategoryId(priceAndDiscount.getTaxCategoryId()); candidate.setCurrencyId(priceAndDiscount.getCurrencyId()); } private IPricingResult getPriceAndDiscount(final PurchaseOrderPricingInfo pricingInfo) { return PurchaseOrderPriceCalculator.builder() .pricingInfo(pricingInfo) .build() .calculatePrice(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\impl\PurchaseCandidateBL.java
1
请完成以下Java代码
public HUDistributeBuilder setContext(final IContextAware context) { _context = context; return this; } public IContextAware getContext() { Check.assumeNotNull(_context, "_context not null"); return _context; } public HUDistributeBuilder setVHUToDistribute(final I_M_HU vhuToDistribute) { _vhuToDistribute = vhuToDistribute; return this; } private I_M_HU getVHUToDistribute() { Check.assumeNotNull(_vhuToDistribute, "_vhuToDistribute not null"); return _vhuToDistribute; } public HUDistributeBuilder setTUsToDistributeOn(final Collection<I_M_HU> tusToDistributeOn) { _tusToDistributeOn = tusToDistributeOn; return this; } private Collection<I_M_HU> getTUsToDistributeOn() { Check.assumeNotEmpty(_tusToDistributeOn, "_tusToDistributeOn not empty"); return _tusToDistributeOn;
} public HUDistributeBuilder setQtyCUsPerTU(final BigDecimal qtyCUsPerTU) { _qtyCUsPerTU = qtyCUsPerTU; return this; } private BigDecimal getQtyCUsPerTU() { Check.assumeNotNull(_qtyCUsPerTU, "_qtyCUsPerTU not null"); Check.assume(_qtyCUsPerTU.signum() > 0, "Qty CUs/TU > 0"); return _qtyCUsPerTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUDistributeBuilder.java
1
请完成以下Java代码
public void setErrorMsg (String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } /** Get Error Msg. @return Error Msg */ public String getErrorMsg () { return (String)get_Value(COLUMNNAME_ErrorMsg); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Unique. @param IsUnique Unique */ public void setIsUnique (boolean IsUnique) { set_Value (COLUMNNAME_IsUnique, Boolean.valueOf(IsUnique)); } /** Get Unique. @return Unique */ public boolean isUnique () { Object oo = get_Value(COLUMNNAME_IsUnique); 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_ValueNoCheck (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () {
Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } @Override public String getBeforeChangeWarning() { return (String)get_Value(COLUMNNAME_BeforeChangeWarning); } @Override public void setBeforeChangeWarning(String BeforeChangeWarning) { set_Value (COLUMNNAME_BeforeChangeWarning, BeforeChangeWarning); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Table.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService customUserDetailsService; @Autowired private DataSource dataSource; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .frameOptions().sameOrigin() .and() .authorizeRequests() .antMatchers("/resources/**", "/webjars/**","/assets/**").permitAll() .antMatchers("/").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .failureUrl("/login?error")
.permitAll() .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .deleteCookies("my-remember-me-cookie") .permitAll() .and() .rememberMe() //.key("my-secure-key") .rememberMeCookieName("my-remember-me-cookie") .tokenRepository(persistentTokenRepository()) .tokenValiditySeconds(24 * 60 * 60) .and() .exceptionHandling() ; } PersistentTokenRepository persistentTokenRepository(){ JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl(); tokenRepositoryImpl.setDataSource(dataSource); return tokenRepositoryImpl; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-thymeleaf-security-demo\src\main\java\net\alanbinu\springbootsecurity\config\WebSecurityConfig.java
2
请完成以下Java代码
public void setDbtrAcct(CashAccountSEPA2 value) { this.dbtrAcct = value; } /** * Gets the value of the ultmtDbtr property. * * @return * possible object is * {@link PartyIdentificationSEPA1 } * */ public PartyIdentificationSEPA1 getUltmtDbtr() { return ultmtDbtr; } /** * Sets the value of the ultmtDbtr property. * * @param value * allowed object is * {@link PartyIdentificationSEPA1 } * */ public void setUltmtDbtr(PartyIdentificationSEPA1 value) { this.ultmtDbtr = value; } /** * Gets the value of the purp property. * * @return * possible object is * {@link PurposeSEPA } * */ public PurposeSEPA getPurp() { return purp; } /** * Sets the value of the purp property. * * @param value * allowed object is * {@link PurposeSEPA } * */ public void setPurp(PurposeSEPA value) { this.purp = value; }
/** * Gets the value of the rmtInf property. * * @return * possible object is * {@link RemittanceInformationSEPA1Choice } * */ public RemittanceInformationSEPA1Choice getRmtInf() { return rmtInf; } /** * Sets the value of the rmtInf property. * * @param value * allowed object is * {@link RemittanceInformationSEPA1Choice } * */ public void setRmtInf(RemittanceInformationSEPA1Choice value) { this.rmtInf = 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\DirectDebitTransactionInformationSDD.java
1
请在Spring Boot框架中完成以下Java代码
public class Knife4jController { /** * Knife4j 测试接口问好 * 来源微信公众号:Java技术栈 * 作者:栈长 */ @ApiImplicitParam(name = "name", value = "名称", required = true) @ApiOperation(value = "公众号Java技术栈向你问好!") @ApiOperationSupport(order = 2, author = "栈长") @GetMapping("/knife4j/hi") public ResponseEntity<String> hello(@RequestParam(value = "name") String name) { return ResponseEntity.ok("Hi:" + name); } /** * Knife4j 测试接口登录 * 来源微信公众号:Java技术栈 * 作者:栈长 */
@ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "用户名", required = true), @ApiImplicitParam(name = "password", value = "密码", required = true) }) @ApiOperation(value = "接口登录!") @ApiOperationSupport(order = 1, author = "栈长") @PostMapping("/knife4j/login") public ResponseEntity<String> login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password) { if (StringUtils.isNotBlank(username) && "javastack".equals(password)) { return ResponseEntity.ok("登录成功:" + username); } return ResponseEntity.ok("用户名或者密码有误:" + username); } }
repos\spring-boot-best-practice-master\spring-boot-knife4j\src\main\java\cn\javastack\springboot\knife4j\api\Knife4jController.java
2
请完成以下Java代码
public class LoginResponse { private String username; private String firstName; private String lastName; private String email; public LoginResponse() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstName() { return firstName;
} public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\security\dto\LoginResponse.java
1
请完成以下Java代码
protected void prepare() { for (ProcessInfoParameter para : getParametersAsArray()) { String name = para.getParameterName(); if (para.getParameter() == null) { log.debug("Null Parameter: " + name); } else if (name.equals(PARAM_HR_Process_ID)) { m_HR_Process_ID = para.getParameterAsInt(); } else { log.error("Unknown Parameter: " + name); } } }
@Override protected String doIt() throws Exception { if (m_HR_Process_ID <= 0) throw new FillMandatoryException(PARAM_HR_Process_ID); MHRProcess process = new MHRProcess(getCtx(), m_HR_Process_ID, get_TrxName()); long start = System.currentTimeMillis(); boolean ok = process.processIt(MHRProcess.ACTION_Complete); process.saveEx(); if (!ok) { throw new AdempiereException(process.getProcessMsg()); } return "@Processed@ " + process.getName() +" - "+(System.currentTimeMillis()-start) + "ms"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\process\PayrollProcessing.java
1
请完成以下Java代码
private TbMsg processException(TbMsg origMsg, Throwable t) { TbMsgMetaData metaData = origMsg.getMetaData().copy(); metaData.putValue(ERROR, t.getClass() + ": " + t.getMessage()); return origMsg.transform() .metaData(metaData) .build(); } Publisher initPubSubClient(TbContext ctx) throws IOException { ProjectTopicName topicName = ProjectTopicName.of(config.getProjectId(), config.getTopicName()); ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream( new ByteArrayInputStream(config.getServiceAccountKey().getBytes())); CredentialsProvider credProvider = FixedCredentialsProvider.create(credentials); var retrySettings = RetrySettings.newBuilder() .setTotalTimeout(Duration.ofSeconds(10))
.setInitialRetryDelay(Duration.ofMillis(50)) .setRetryDelayMultiplier(1.1) .setMaxRetryDelay(Duration.ofSeconds(2)) .setInitialRpcTimeout(Duration.ofSeconds(2)) .setRpcTimeoutMultiplier(1) .setMaxRpcTimeout(Duration.ofSeconds(10)) .build(); return Publisher.newBuilder(topicName) .setCredentialsProvider(credProvider) .setRetrySettings(retrySettings) .setExecutorProvider(FixedExecutorProvider.create(ctx.getPubSubRuleNodeExecutorProvider().getExecutor())) .build(); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\gcp\pubsub\TbPubSubNode.java
1
请完成以下Java代码
private static String readContentFromPipedInputStream(PipedInputStream stream) throws IOException { StringBuffer contentStringBuffer = new StringBuffer(); try { Thread pipeReader = new Thread(() -> { try { contentStringBuffer.append(readContent(stream)); } catch (IOException e) { throw new RuntimeException(e); } }); pipeReader.start(); pipeReader.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { stream.close(); } return String.valueOf(contentStringBuffer); }
private static String readContent(InputStream stream) throws IOException { StringBuffer contentStringBuffer = new StringBuffer(); byte[] tmp = new byte[stream.available()]; int byteCount = stream.read(tmp, 0, tmp.length); logger.info(String.format("read %d bytes from the stream\n", byteCount)); contentStringBuffer.append(new String(tmp)); return String.valueOf(contentStringBuffer); } public static void main(String[] args) throws IOException, InterruptedException { WebClient webClient = getWebClient(); InputStream inputStream = getResponseAsInputStream(webClient, REQUEST_ENDPOINT); Thread.sleep(3000); String content = readContentFromPipedInputStream((PipedInputStream) inputStream); logger.info("response content: \n{}", content.replace("}", "}\n")); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-3\src\main\java\com\baeldung\databuffer\DataBufferToInputStream.java
1
请完成以下Java代码
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } public String getRootProcessInstanceId() {
return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public static AttachmentDto fromAttachment(Attachment attachment) { AttachmentDto dto = new AttachmentDto(); dto.id = attachment.getId(); dto.name = attachment.getName(); dto.type = attachment.getType(); dto.description = attachment.getDescription(); dto.taskId = attachment.getTaskId(); dto.url = attachment.getUrl(); dto.createTime = attachment.getCreateTime(); dto.removalTime = attachment.getRemovalTime(); dto.rootProcessInstanceId = attachment.getRootProcessInstanceId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\AttachmentDto.java
1
请完成以下Java代码
protected Object evaluate(String script, String language, Bindings bindings) { ScriptEngine scriptEngine = getEngineByName(language); try { return scriptEngine.eval(script, bindings); } catch (ScriptException e) { throw new ActivitiException("problem evaluating script: " + e.getMessage(), e); } } protected ScriptEngine getEngineByName(String language) { ScriptEngine scriptEngine = null; if (cacheScriptingEngines) { scriptEngine = cachedEngines.get(language); if (scriptEngine == null) { scriptEngine = scriptEngineManager.getEngineByName(language); if (scriptEngine != null) { // ACT-1858: Special handling for groovy engine regarding GC if (GROOVY_SCRIPTING_LANGUAGE.equals(language)) { try { scriptEngine .getContext() .setAttribute("#jsr223.groovy.engine.keep.globals", "weak", ScriptContext.ENGINE_SCOPE); } catch (Exception ignore) { // ignore this, in case engine doesn't support the // passed attribute } } // Check if script-engine allows caching, using "THREADING" // parameter as defined in spec Object threadingParameter = scriptEngine.getFactory().getParameter("THREADING"); if (threadingParameter != null) { // Add engine to cache as any non-null result from the // threading-parameter indicates at least MT-access cachedEngines.put(language, scriptEngine); }
} } } else { scriptEngine = scriptEngineManager.getEngineByName(language); } if (scriptEngine == null) { throw new ActivitiException("Can't find scripting engine for '" + language + "'"); } return scriptEngine; } /** override to build a spring aware ScriptingEngines */ protected Bindings createBindings(VariableScope variableScope) { return scriptBindingsFactory.createBindings(variableScope); } /** override to build a spring aware ScriptingEngines */ protected Bindings createBindings(VariableScope variableScope, boolean storeScriptVariables) { return scriptBindingsFactory.createBindings(variableScope, storeScriptVariables); } public ScriptBindingsFactory getScriptBindingsFactory() { return scriptBindingsFactory; } public void setScriptBindingsFactory(ScriptBindingsFactory scriptBindingsFactory) { this.scriptBindingsFactory = scriptBindingsFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptingEngines.java
1
请完成以下Java代码
private I_C_Order copyProposalHeader(@NonNull final I_C_Order fromProposal) { final I_C_Order newSalesOrder = InterfaceWrapperHelper.copy() .setFrom(fromProposal) .setSkipCalculatedColumns(true) .copyToNew(I_C_Order.class); orderBL.setDocTypeTargetIdAndUpdateDescription(newSalesOrder, newOrderDocTypeId); newSalesOrder.setC_DocType_ID(newOrderDocTypeId.getRepoId()); if (newOrderDateOrdered != null) { newSalesOrder.setDateOrdered(newOrderDateOrdered); } if (!Check.isBlank(poReference)) { newSalesOrder.setPOReference(poReference); } newSalesOrder.setDatePromised(fromProposal.getDatePromised()); newSalesOrder.setPreparationDate(fromProposal.getPreparationDate()); newSalesOrder.setDocStatus(DocStatus.Drafted.getCode()); newSalesOrder.setDocAction(X_C_Order.DOCACTION_Complete); newSalesOrder.setRef_Proposal_ID(fromProposal.getC_Order_ID()); orderDAO.save(newSalesOrder); fromProposal.setRef_Order_ID(newSalesOrder.getC_Order_ID()); orderDAO.save(fromProposal); return newSalesOrder; } private void copyProposalLines( @NonNull final I_C_Order fromProposal, @NonNull final I_C_Order newSalesOrder) { CopyRecordFactory.getCopyRecordSupport(I_C_Order.Table_Name) .onChildRecordCopied(this::onRecordCopied) .copyChildren( InterfaceWrapperHelper.getPO(newSalesOrder), InterfaceWrapperHelper.getPO(fromProposal)); } private void onRecordCopied(@NonNull final PO to, @NonNull final PO from, @NonNull final CopyTemplate template) { if (InterfaceWrapperHelper.isInstanceOf(to, I_C_OrderLine.class) && InterfaceWrapperHelper.isInstanceOf(from, I_C_OrderLine.class)) { final I_C_OrderLine newSalesOrderLine = InterfaceWrapperHelper.create(to, I_C_OrderLine.class); final I_C_OrderLine fromProposalLine = InterfaceWrapperHelper.create(from, I_C_OrderLine.class); newSalesOrderLine.setRef_ProposalLine_ID(fromProposalLine.getC_OrderLine_ID());
final I_C_Order fromProposal = fromProposalLine.getC_Order(); final DocTypeId proposalDocType = DocTypeId.ofRepoId(fromProposal.getC_DocType_ID()); if (isKeepProposalPrices && docTypeBL.isSalesQuotation(proposalDocType)) { newSalesOrderLine.setIsManualPrice(true); newSalesOrderLine.setPriceActual(fromProposalLine.getPriceActual()); } } } private void completeSalesOrderIfNeeded(final I_C_Order newSalesOrder) { if (completeIt) { documentBL.processEx(newSalesOrder, IDocument.ACTION_Complete, IDocument.STATUS_Completed); } else { newSalesOrder.setDocAction(IDocument.ACTION_Prepare); orderDAO.save(newSalesOrder); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\CreateSalesOrderFromProposalCommand.java
1
请完成以下Java代码
public class Foo { private long id; @Schema(name = "name", type = "array", example = "[\"str1\", \"str2\", \"str3\"]") private List<String> name; public Foo() { super(); } public Foo(final long id, final List<String> name) { super(); this.id = id; this.name = name; } // public long getId() { return id;
} public void setId(final long id) { this.id = id; } public List<String> getName() { return name; } public void setName(final List<String> name) { this.name = name; } }
repos\tutorials-master\spring-boot-modules\spring-boot-swagger-2\src\main\java\com\baeldung\swagger2bootmvc\model\Foo.java
1
请完成以下Java代码
private static Stream<HttpExchange> filter(String[] params, Stream<HttpExchange> stream) { if (params.length == 0) { return stream; } String statusQuery = params[0]; if (null != statusQuery && !statusQuery.isEmpty()) { statusQuery = statusQuery.toLowerCase().trim(); switch (statusQuery) { case "error": stream = stream.filter(httpTrace -> { int status = httpTrace.getResponse().getStatus(); return status >= 404 && status < 501; }); break; case "warn": stream = stream.filter(httpTrace -> { int status = httpTrace.getResponse().getStatus(); return status >= 201 && status < 404; }); break;
case "success": stream = stream.filter(httpTrace -> { int status = httpTrace.getResponse().getStatus(); return status == 200; }); break; case "all": default: break; } return stream; } return stream; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\actuator\httptrace\CustomInMemoryHttpTraceRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class ExchangeValue { @Id private Long id; @Column(name = "currency_from") private String from; @Column(name = "currency_to") private String to; private BigDecimal conversionMultiple; private int port; public ExchangeValue() { } public ExchangeValue(Long id, String from, String to, BigDecimal conversionMultiple) { super(); this.id = id; this.from = from; this.to = to; this.conversionMultiple = conversionMultiple; } public Long getId() { return id; } public String getFrom() { return from; }
public String getTo() { return to; } public BigDecimal getConversionMultiple() { return conversionMultiple; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
repos\spring-boot-examples-master\spring-boot-basic-microservice\spring-boot-microservice-forex-service\src\main\java\com\in28minutes\springboot\microservice\example\forex\ExchangeValue.java
2
请完成以下Java代码
public class MessageThrowingEventListener extends BaseDelegateEventListener { protected String messageName; protected Class<?> entityClass; @Override public void onEvent(ActivitiEvent event) { if (isValidEvent(event)) { if (event.getProcessInstanceId() == null) { throw new ActivitiIllegalArgumentException( "Cannot throw process-instance scoped message, since the dispatched event is not part of an ongoing process instance" ); } EventSubscriptionEntityManager eventSubscriptionEntityManager = Context.getCommandContext().getEventSubscriptionEntityManager(); List<MessageEventSubscriptionEntity> subscriptionEntities = eventSubscriptionEntityManager.findMessageEventSubscriptionsByProcessInstanceAndEventName( event.getProcessInstanceId(), messageName );
for (EventSubscriptionEntity messageEventSubscriptionEntity : subscriptionEntities) { eventSubscriptionEntityManager.eventReceived(messageEventSubscriptionEntity, null, false); } } } public void setMessageName(String messageName) { this.messageName = messageName; } @Override public boolean isFailOnException() { return true; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\MessageThrowingEventListener.java
1
请完成以下Java代码
public long position() throws IOException { assertNotClosed(); return this.position; } @Override public SeekableByteChannel position(long position) throws IOException { assertNotClosed(); if (position < 0 || position >= this.size) { throw new IllegalArgumentException("Position must be in bounds"); } this.position = position; return this; } @Override public long size() throws IOException { assertNotClosed(); return this.size; } @Override public SeekableByteChannel truncate(long size) throws IOException { throw new NonWritableChannelException(); } private void assertNotClosed() throws ClosedChannelException { if (this.closed) { throw new ClosedChannelException(); } } /** * Resources used by the channel and suitable for registration with a {@link Cleaner}. */ static class Resources implements Runnable { private final ZipContent zipContent; private final CloseableDataBlock data; Resources(Path path, String nestedEntryName) throws IOException { this.zipContent = ZipContent.open(path, nestedEntryName); this.data = this.zipContent.openRawZipData(); } DataBlock getData() {
return this.data; } @Override public void run() { releaseAll(); } private void releaseAll() { IOException exception = null; try { this.data.close(); } catch (IOException ex) { exception = ex; } try { this.zipContent.close(); } catch (IOException ex) { if (exception != null) { ex.addSuppressed(exception); } exception = ex; } if (exception != null) { throw new UncheckedIOException(exception); } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedByteChannel.java
1
请完成以下Java代码
public ZonedDateTime getDateTrx() { final ZonedDateTime date = dateRef.get(); if (date != null) { return date; } return de.metas.common.util.time.SystemTime.asZonedDateTime(); } /** * Temporary override current date provider by given date. * * @param date * @return */
public ITemporaryDateTrx temporarySet(@NonNull final Date date) { return temporarySet(TimeUtil.asZonedDateTime(date)); } public ITemporaryDateTrx temporarySet(@NonNull final ZonedDateTime date) { final ZonedDateTime dateOld = dateRef.get(); dateRef.set(date); return () -> dateRef.set(dateOld); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUContextDateTrxProvider.java
1
请在Spring Boot框架中完成以下Java代码
public String getIBAN() { return iban; } /** * Sets the value of the iban property. * * @param value * allowed object is * {@link String } * */ public void setIBAN(String value) { this.iban = value; } /** * Name of the bank account holder. * * @return * possible object is * {@link String } *
*/ public String getBankAccountOwner() { return bankAccountOwner; } /** * Sets the value of the bankAccountOwner property. * * @param value * allowed object is * {@link String } * */ public void setBankAccountOwner(String value) { this.bankAccountOwner = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AccountType.java
2
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractHibernateService<T extends Serializable> extends AbstractService<T> implements IOperations<T> { @Override public T findOne(final long id) { return super.findOne(id); } @Override public List<T> findAll() { return super.findAll(); } @Override public void create(final T entity) { super.create(entity); }
@Override public T update(final T entity) { return super.update(entity); } @Override public void delete(final T entity) { super.delete(entity); } @Override public void deleteById(final long entityId) { super.deleteById(entityId); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\persistence\service\common\AbstractHibernateService.java
2
请完成以下Java代码
public int getGL_Fund_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Fund Restriction. @param GL_FundRestriction_ID Restriction of Funds */ public void setGL_FundRestriction_ID (int GL_FundRestriction_ID) { if (GL_FundRestriction_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, Integer.valueOf(GL_FundRestriction_ID)); } /** Get Fund Restriction. @return Restriction of Funds */ public int getGL_FundRestriction_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_FundRestriction_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); }
/** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_FundRestriction.java
1
请完成以下Java代码
public boolean isCancelActivity() { return cancelActivity; } public void setCancelActivity(boolean cancelActivity) { this.cancelActivity = cancelActivity; } public boolean hasErrorEventDefinition() { if (this.eventDefinitions != null && !this.eventDefinitions.isEmpty()) { return this.eventDefinitions.stream().anyMatch(eventDefinition -> ErrorEventDefinition.class.isInstance(eventDefinition) ); } return false;
} public BoundaryEvent clone() { BoundaryEvent clone = new BoundaryEvent(); clone.setValues(this); return clone; } public void setValues(BoundaryEvent otherEvent) { super.setValues(otherEvent); setAttachedToRefId(otherEvent.getAttachedToRefId()); setAttachedToRef(otherEvent.getAttachedToRef()); setCancelActivity(otherEvent.isCancelActivity()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BoundaryEvent.java
1
请完成以下Java代码
protected CommandContext getCommandContext() { return Context.getCommandContext(); } protected Object getResultElementItem(Map<String, Object> availableVariables) { if (hasOutputDataItem()) { return availableVariables.get(getOutputDataItem()); } else { //exclude from the result all the built-in multi-instances variables //and loopDataOutputRef itself that may exist in the context depending // on the variable propagation List<String> resultItemExclusions = Arrays.asList( getLoopDataOutputRef(), getCollectionElementIndexVariable(), NUMBER_OF_INSTANCES, NUMBER_OF_COMPLETED_INSTANCES,
NUMBER_OF_ACTIVE_INSTANCES ); HashMap<String, Object> resultItem = new HashMap<>(availableVariables); resultItemExclusions.forEach(resultItem.keySet()::remove); return resultItem; } } protected void propagateLoopDataOutputRefToProcessInstance(ExecutionEntity miRootExecution) { if (hasLoopDataOutputRef()) { miRootExecution .getProcessInstance() .setVariable(getLoopDataOutputRef(), miRootExecution.getVariable(getLoopDataOutputRef())); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.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 Produkt-Zuordnung. @param M_Product_Mapping_ID Produkt-Zuordnung */ @Override public void setM_Product_Mapping_ID (int M_Product_Mapping_ID) { if (M_Product_Mapping_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Mapping_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Mapping_ID, Integer.valueOf(M_Product_Mapping_ID)); } /** Get Produkt-Zuordnung. @return Produkt-Zuordnung */ @Override public int getM_Product_Mapping_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Mapping_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suchschlüssel. @param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\product\model\X_M_Product_Mapping.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .addValue(sql) .add("params", sqlParams) .toString(); } @Override public int hashCode() { return Objects.hash(sql, sqlParams); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof TypedSqlQueryFilter) { final TypedSqlQueryFilter<?> other = (TypedSqlQueryFilter<?>)obj; return Objects.equals(sql, other.sql) && Objects.equals(sqlParams, other.sqlParams); } else { return false; } } @Override public String getSql()
{ return sql; } @Override public List<Object> getSqlParams(final Properties ctx_NOTUSED) { return sqlParams; } @Override public boolean accept(final T model) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\TypedSqlQueryFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class ErrorProperties { /** * Path of the error controller. */ @Value("${error.path:/error}") private String path = "/error"; /** * Include the "exception" attribute. */ private boolean includeException; /** * When to include the "trace" attribute. */ private IncludeAttribute includeStacktrace = IncludeAttribute.NEVER; /** * When to include "message" attribute. */ private IncludeAttribute includeMessage = IncludeAttribute.NEVER; /** * When to include "errors" attribute. */ private IncludeAttribute includeBindingErrors = IncludeAttribute.NEVER; /** * When to include "path" attribute. */ private IncludeAttribute includePath = IncludeAttribute.ALWAYS; private final Whitelabel whitelabel = new Whitelabel(); public String getPath() { return this.path; } public void setPath(String path) { this.path = path; } public boolean isIncludeException() { return this.includeException; } public void setIncludeException(boolean includeException) { this.includeException = includeException; } public IncludeAttribute getIncludeStacktrace() { return this.includeStacktrace; } public void setIncludeStacktrace(IncludeAttribute includeStacktrace) { this.includeStacktrace = includeStacktrace; } public IncludeAttribute getIncludeMessage() { return this.includeMessage; } public void setIncludeMessage(IncludeAttribute includeMessage) { this.includeMessage = includeMessage; } public IncludeAttribute getIncludeBindingErrors() { return this.includeBindingErrors;
} public void setIncludeBindingErrors(IncludeAttribute includeBindingErrors) { this.includeBindingErrors = includeBindingErrors; } public IncludeAttribute getIncludePath() { return this.includePath; } public void setIncludePath(IncludeAttribute includePath) { this.includePath = includePath; } public Whitelabel getWhitelabel() { return this.whitelabel; } /** * Include error attributes options. */ public enum IncludeAttribute { /** * Never add error attribute. */ NEVER, /** * Always add error attribute. */ ALWAYS, /** * Add error attribute when the appropriate request parameter is not "false". */ ON_PARAM } public static class Whitelabel { /** * Whether to enable the default error page displayed in browsers in case of a * server error. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\ErrorProperties.java
2
请完成以下Java代码
public boolean ask(int WindowNo, String AD_Message) { throw new UnsupportedOperationException("not implemented"); } @Override public boolean ask(int WindowNo, String AD_Message, String message) { throw new UnsupportedOperationException("not implemented"); } @Override public void warn(int WindowNo, String AD_Message) { logger.warn(AD_Message); } @Override public void warn(int WindowNo, String AD_Message, String message) { logger.warn("" + AD_Message + ": " + message); } @Override public void error(int WIndowNo, String AD_Message) { logger.warn("" + AD_Message); } @Override public void error(int WIndowNo, String AD_Message, String message) { logger.error("" + AD_Message + ": " + message); } @Override public void download(byte[] data, String contentType, String filename) { throw new UnsupportedOperationException("not implemented"); } @Override public void downloadNow(InputStream content, String contentType, String filename) { throw new UnsupportedOperationException("not implemented"); } @Override public String getClientInfo() { // implementation basically copied from SwingClientUI final String javaVersion = System.getProperty("java.version"); return new StringBuilder("!! NO UI REGISTERED YET !!, java.version=").append(javaVersion).toString(); }
@Override public void showWindow(Object model) { throw new UnsupportedOperationException("Not implemented: ClientUI.showWindow()"); } @Override public IClientUIInvoker invoke() { throw new UnsupportedOperationException("not implemented"); } @Override public IClientUIAsyncInvoker invokeAsync() { throw new UnsupportedOperationException("not implemented"); } @Override public void showURL(String url) { System.err.println("Showing URL is not supported on server side: " + url); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\impl\ClientUI.java
1
请完成以下Java代码
public static <K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> input) { return sortMapByValue(input, true); } public static String max(Map<String, Double> scoreMap) { double max = Double.NEGATIVE_INFINITY; String best = null; for (Map.Entry<String, Double> entry : scoreMap.entrySet()) { Double score = entry.getValue(); if (score > max) { max = score; best = entry.getKey(); } } return best; } /** * 分割数组为两个数组 * @param src 原数组 * @param rate 第一个数组所占的比例 * @return 两个数组 */ public static String[][] spiltArray(String[] src, double rate) { assert 0 <= rate && rate <= 1; String[][] output = new String[2][]; output[0] = new String[(int) (src.length * rate)]; output[1] = new String[src.length - output[0].length]; System.arraycopy(src, 0, output[0], 0, output[0].length); System.arraycopy(src, output[0].length, output[1], 0, output[1].length); return output; }
/** * 分割Map,其中旧map直接被改变 * @param src * @param rate * @return */ public static Map<String, String[]> splitMap(Map<String, String[]> src, double rate) { assert 0 <= rate && rate <= 1; Map<String, String[]> output = new TreeMap<String, String[]>(); for (Map.Entry<String, String[]> entry : src.entrySet()) { String[][] array = spiltArray(entry.getValue(), rate); output.put(entry.getKey(), array[0]); entry.setValue(array[1]); } return output; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\utilities\CollectionUtility.java
1
请完成以下Java代码
public void setC_Country_ID (int C_Country_ID) { if (C_Country_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Country_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Country_ID, Integer.valueOf(C_Country_ID)); } /** Get Land. @return Land */ @Override public int getC_Country_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Country Sequence. @param C_Country_Sequence_ID Country Sequence */ @Override public void setC_Country_Sequence_ID (int C_Country_Sequence_ID) { if (C_Country_Sequence_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Country_Sequence_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Country_Sequence_ID, Integer.valueOf(C_Country_Sequence_ID)); } /** Get Country Sequence. @return Country Sequence */ @Override public int getC_Country_Sequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_Sequence_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Adress-Druckformat. @param DisplaySequence Format for printing this Address */ @Override public void setDisplaySequence (java.lang.String DisplaySequence) { set_Value (COLUMNNAME_DisplaySequence, DisplaySequence); } /** Get Adress-Druckformat. @return Format for printing this Address */
@Override public java.lang.String getDisplaySequence () { return (java.lang.String)get_Value(COLUMNNAME_DisplaySequence); } /** Set Local Address Format. @param DisplaySequenceLocal Format for printing this Address locally */ @Override public void setDisplaySequenceLocal (java.lang.String DisplaySequenceLocal) { set_Value (COLUMNNAME_DisplaySequenceLocal, DisplaySequenceLocal); } /** Get Local Address Format. @return Format for printing this Address locally */ @Override public java.lang.String getDisplaySequenceLocal () { return (java.lang.String)get_Value(COLUMNNAME_DisplaySequenceLocal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country_Sequence.java
1
请完成以下Java代码
public class Coffee { private String brand; private String origin; private String characteristics; public Coffee() { } public Coffee(String brand, String origin, String characteristics) { this.brand = brand; this.origin = origin; this.characteristics = characteristics; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; }
public String getCharacteristics() { return characteristics; } public void setCharacteristics(String characteristics) { this.characteristics = characteristics; } @Override public String toString() { return "Coffee [brand=" + getBrand() + ", origin=" + getOrigin() + ", characteristics=" + getCharacteristics() + "]"; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\bootbatch\Coffee.java
1
请完成以下Java代码
public void addExitCriterion(Criterion exitCriterion) { exitCriteria.add(exitCriterion); } public Integer getDisplayOrder() { return displayOrder; } public void setDisplayOrder(Integer displayOrder) { this.displayOrder = displayOrder; } public String getIncludeInStageOverview() { return includeInStageOverview; } public void setIncludeInStageOverview(String includeInStageOverview) { this.includeInStageOverview = includeInStageOverview; } @Override
public List<Criterion> getExitCriteria() { return exitCriteria; } @Override public void setExitCriteria(List<Criterion> exitCriteria) { this.exitCriteria = exitCriteria; } public String getBusinessStatus() { return businessStatus; } public void setBusinessStatus(String businessStatus) { this.businessStatus = businessStatus; } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Stage.java
1
请完成以下Java代码
public IncidentQuery causeIncidentId(String causeIncidentId) { this.causeIncidentId = causeIncidentId; return this; } public IncidentQuery rootCauseIncidentId(String rootCauseIncidentId) { this.rootCauseIncidentId = rootCauseIncidentId; return this; } public IncidentQuery configuration(String configuration) { this.configuration = configuration; return this; } public IncidentQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; return this; } public IncidentQuery jobDefinitionIdIn(String... jobDefinitionIds) { ensureNotNull("jobDefinitionIds", (Object[]) jobDefinitionIds); this.jobDefinitionIds = jobDefinitionIds; return this; } //ordering //////////////////////////////////////////////////// public IncidentQuery orderByIncidentId() { orderBy(IncidentQueryProperty.INCIDENT_ID); return this; } public IncidentQuery orderByIncidentTimestamp() { orderBy(IncidentQueryProperty.INCIDENT_TIMESTAMP); return this; } public IncidentQuery orderByIncidentType() { orderBy(IncidentQueryProperty.INCIDENT_TYPE); return this; } public IncidentQuery orderByExecutionId() { orderBy(IncidentQueryProperty.EXECUTION_ID); return this; } public IncidentQuery orderByActivityId() { orderBy(IncidentQueryProperty.ACTIVITY_ID); return this; } public IncidentQuery orderByProcessInstanceId() { orderBy(IncidentQueryProperty.PROCESS_INSTANCE_ID); return this; } public IncidentQuery orderByProcessDefinitionId() { orderBy(IncidentQueryProperty.PROCESS_DEFINITION_ID); return this; } public IncidentQuery orderByCauseIncidentId() { orderBy(IncidentQueryProperty.CAUSE_INCIDENT_ID); return this; } public IncidentQuery orderByRootCauseIncidentId() {
orderBy(IncidentQueryProperty.ROOT_CAUSE_INCIDENT_ID); return this; } public IncidentQuery orderByConfiguration() { orderBy(IncidentQueryProperty.CONFIGURATION); return this; } public IncidentQuery orderByTenantId() { return orderBy(IncidentQueryProperty.TENANT_ID); } @Override public IncidentQuery orderByIncidentMessage() { return orderBy(IncidentQueryProperty.INCIDENT_MESSAGE); } //results //////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getIncidentManager() .findIncidentCountByQueryCriteria(this); } @Override public List<Incident> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getIncidentManager() .findIncidentByQueryCriteria(this, page); } public String[] getProcessDefinitionKeys() { return processDefinitionKeys; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IncidentQueryImpl.java
1
请完成以下Java代码
public String getName() { return name; } public int getAge() { return age; } @Override public int hashCode() { int hash = 3; hash = 23 * hash + Objects.hashCode(this.name); hash = 23 * hash + this.age; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false;
} if (getClass() != obj.getClass()) { return false; } final AuthorId other = (AuthorId) obj; if (this.age != other.age) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return true; } @Override public String toString() { return "AuthorId{" + "name=" + name + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddable\src\main\java\com\bookstore\entity\AuthorId.java
1
请在Spring Boot框架中完成以下Java代码
public UUID getId() { return _id; } public void setId(UUID _id) { this._id = _id; } public ArticleMapping customerId(String customerId) { this.customerId = customerId; return this; } /** * eindeutige Artikelnummer aus WaWi * @return customerId **/ @Schema(example = "43435", required = true, description = "eindeutige Artikelnummer aus WaWi") public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public ArticleMapping updated(OffsetDateTime updated) { this.updated = updated; return this; } /** * Der Zeitstempel der letzten Änderung * @return updated **/ @Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArticleMapping articleMapping = (ArticleMapping) o; return Objects.equals(this._id, articleMapping._id) && Objects.equals(this.customerId, articleMapping.customerId) && Objects.equals(this.updated, articleMapping.updated);
} @Override public int hashCode() { return Objects.hash(_id, customerId, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ArticleMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\ArticleMapping.java
2
请在Spring Boot框架中完成以下Java代码
public int batchSize() { return obtain(AtlasProperties::getBatchSize, AtlasConfig.super::batchSize); } @Override public String uri() { return obtain(AtlasProperties::getUri, AtlasConfig.super::uri); } @Override public Duration meterTTL() { return obtain(AtlasProperties::getMeterTimeToLive, AtlasConfig.super::meterTTL); } @Override public boolean lwcEnabled() { return obtain(AtlasProperties::isLwcEnabled, AtlasConfig.super::lwcEnabled); } @Override public Duration lwcStep() { return obtain(AtlasProperties::getLwcStep, AtlasConfig.super::lwcStep); } @Override public boolean lwcIgnorePublishStep() { return obtain(AtlasProperties::isLwcIgnorePublishStep, AtlasConfig.super::lwcIgnorePublishStep); } @Override public Duration configRefreshFrequency() { return obtain(AtlasProperties::getConfigRefreshFrequency, AtlasConfig.super::configRefreshFrequency); }
@Override public Duration configTTL() { return obtain(AtlasProperties::getConfigTimeToLive, AtlasConfig.super::configTTL); } @Override public String configUri() { return obtain(AtlasProperties::getConfigUri, AtlasConfig.super::configUri); } @Override public String evalUri() { return obtain(AtlasProperties::getEvalUri, AtlasConfig.super::evalUri); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasPropertiesConfigAdapter.java
2
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Gross Amount. @param GrossRAmt Gross Remuneration Amount */ public void setGrossRAmt (BigDecimal GrossRAmt) { set_Value (COLUMNNAME_GrossRAmt, GrossRAmt); } /** Get Gross Amount. @return Gross Remuneration Amount */ public BigDecimal getGrossRAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrossRAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Gross Cost. @param GrossRCost Gross Remuneration Costs */ public void setGrossRCost (BigDecimal GrossRCost) { set_Value (COLUMNNAME_GrossRCost, GrossRCost); } /** Get Gross Cost. @return Gross Remuneration Costs */ public BigDecimal getGrossRCost () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrossRCost); if (bd == null) return Env.ZERO; return bd; } /** Set Overtime Amount. @param OvertimeAmt Hourly Overtime Rate */ public void setOvertimeAmt (BigDecimal OvertimeAmt) { set_Value (COLUMNNAME_OvertimeAmt, OvertimeAmt); } /** Get Overtime Amount. @return Hourly Overtime Rate */ public BigDecimal getOvertimeAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Overtime Cost. @param OvertimeCost Hourly Overtime Cost */ public void setOvertimeCost (BigDecimal OvertimeCost) { set_Value (COLUMNNAME_OvertimeCost, OvertimeCost); } /** Get Overtime Cost. @return Hourly Overtime Cost */
public BigDecimal getOvertimeCost () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeCost); if (bd == null) return Env.ZERO; return bd; } /** 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 Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UserRemuneration.java
1