instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public JdbcCursorItemReader<Product> dbReader() {
return new JdbcCursorItemReaderBuilder<Product>()
.name("dbReader")
.dataSource(dataSource())
.sql("SELECT productid, productname, stock, price FROM products")
.rowMapper((rs, rowNum) -> new Product(
rs.getLong("productid"),
rs.getString("productname"),
rs.getInt("stock"),
rs.getBigDecimal("price")
))
.build();
}
@Bean
public CompositeItemReader<Product> compositeReader() {
return new CompositeItemReader<>(Arrays.asList(fileReader(), dbReader()));
}
@Bean
public ItemWriter<Product> productWriter() {
return items -> {
for (Product product : items) {
System.out.println("Writing product: " + product);
} | };
}
@Bean
public Step step(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("compositeReader") ItemReader<Product> compositeReader, ItemWriter<Product> productWriter) {
return new StepBuilder("productStep", jobRepository)
.<Product, Product>chunk(10, transactionManager)
.reader(compositeReader)
.writer(productWriter)
.build();
}
@Bean
public Job productJob(JobRepository jobRepository, Step step) {
return new JobBuilder("productJob", jobRepository)
.start(step)
.build();
}
} | repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\batch\CompositeItemReaderConfig.java | 2 |
请完成以下Java代码 | public AssetProfile findDefaultEntityByTenantId(UUID tenantId) {
return findDefaultAssetProfile(TenantId.fromUUID(tenantId));
}
@Override
public List<AssetProfileInfo> findByTenantAndImageLink(TenantId tenantId, String imageLink, int limit) {
return assetProfileRepository.findByTenantAndImageLink(tenantId.getId(), imageLink, PageRequest.of(0, limit));
}
@Override
public List<AssetProfileInfo> findByImageLink(String imageLink, int limit) {
return assetProfileRepository.findByImageLink(imageLink, PageRequest.of(0, limit));
}
@Override | public PageData<AssetProfile> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<AssetProfileFields> findNextBatch(UUID id, int batchSize) {
return assetProfileRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET_PROFILE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\asset\JpaAssetProfileDao.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public String toString() { | return getClass() + " - " + type;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventImpl.java | 1 |
请完成以下Java代码 | private static LocalDateTime max(final Collection<LocalDateTime> dates)
{
Check.assumeNotEmpty(dates, "dates is not empty");
return dates.stream().max(Comparator.naturalOrder()).get();
}
//
//
//
//
//
public static class DateSequenceGeneratorBuilder
{
public DateSequenceGeneratorBuilder byDay()
{
return incrementor(CalendarIncrementors.dayByDay());
}
/**
* Iterate each <code>day</code> days.
*
* @param day
* @return this
*/
public DateSequenceGeneratorBuilder byNthDay(final int day)
{
return incrementor(CalendarIncrementors.eachNthDay(day));
}
public DateSequenceGeneratorBuilder byWeeks(final int week, final DayOfWeek dayOfWeek)
{
return incrementor(CalendarIncrementors.eachNthWeek(week, dayOfWeek));
}
public DateSequenceGeneratorBuilder byMonths(final int months, final int dayOfMonth)
{
return incrementor(CalendarIncrementors.eachNthMonth(months, dayOfMonth));
}
public DateSequenceGeneratorBuilder frequency(@NonNull final Frequency frequency)
{
incrementor(createCalendarIncrementor(frequency));
exploder(createDateSequenceExploder(frequency));
return this;
} | private static ICalendarIncrementor createCalendarIncrementor(final Frequency frequency)
{
if (frequency.isWeekly())
{
return CalendarIncrementors.eachNthWeek(frequency.getEveryNthWeek(), DayOfWeek.MONDAY);
}
else if (frequency.isMonthly())
{
return CalendarIncrementors.eachNthMonth(frequency.getEveryNthMonth(), 1); // every given month, 1st day
}
else
{
throw new IllegalArgumentException("Frequency type not supported for " + frequency);
}
}
private static IDateSequenceExploder createDateSequenceExploder(final Frequency frequency)
{
if (frequency.isWeekly())
{
if (frequency.isOnlySomeDaysOfTheWeek())
{
return DaysOfWeekExploder.of(frequency.getOnlyDaysOfWeek());
}
else
{
return DaysOfWeekExploder.ALL_DAYS_OF_WEEK;
}
}
else if (frequency.isMonthly())
{
return DaysOfMonthExploder.of(frequency.getOnlyDaysOfMonth());
}
else
{
throw new IllegalArgumentException("Frequency type not supported for " + frequency);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DateSequenceGenerator.java | 1 |
请完成以下Java代码 | public void changePriceIfNeeded(@NonNull final I_C_Flatrate_Term contract, final BigDecimal priceActual)
{
if (priceActual != null)
{
changeFlatrateTermPrice(contract, priceActual);
subscriptionBL.createPriceChange(contract);
}
}
public void changeQtyIfNeeded(@NonNull final I_C_Flatrate_Term contract, final BigDecimal plannedQtyPerUnit)
{
if (plannedQtyPerUnit != null)
{
changeFlatrateTermQty(contract, plannedQtyPerUnit);
subscriptionBL.createQtyChange(contract, plannedQtyPerUnit);
changeQtyInSubscriptionProgressOfFlatrateTerm(contract, plannedQtyPerUnit);
}
}
private void changeFlatrateTermPrice(@NonNull final I_C_Flatrate_Term term, @NonNull final BigDecimal price)
{
term.setPriceActual(price);
InterfaceWrapperHelper.save(term);
invalidateInvoiceCandidatesOfFlatrateTerm(term);
}
private void changeFlatrateTermQty(@NonNull final I_C_Flatrate_Term term, @NonNull final BigDecimal qty)
{
term.setPlannedQtyPerUnit(qty);
InterfaceWrapperHelper.save(term); | invalidateInvoiceCandidatesOfFlatrateTerm(term);
}
private void invalidateInvoiceCandidatesOfFlatrateTerm(@NonNull final I_C_Flatrate_Term term)
{
Services.get(IInvoiceCandidateHandlerBL.class).invalidateCandidatesFor(term);
}
private void changeQtyInSubscriptionProgressOfFlatrateTerm(@NonNull final I_C_Flatrate_Term term, @NonNull final BigDecimal qty)
{
final ISubscriptionDAO subscriptionPA = Services.get(ISubscriptionDAO.class);
final List<I_C_SubscriptionProgress> deliveries = subscriptionPA.retrieveSubscriptionProgresses(SubscriptionProgressQuery.builder()
.term(term)
.excludedStatus(X_C_SubscriptionProgress.STATUS_Done)
.excludedStatus(X_C_SubscriptionProgress.STATUS_Delivered)
.excludedStatus(X_C_SubscriptionProgress.STATUS_InPicking)
.build());
deliveries.forEach(delivery -> {
delivery.setQty(qty);
InterfaceWrapperHelper.save(delivery);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\ContractChangePriceQtyService.java | 1 |
请完成以下Java代码 | public long getCreatedTime() {
return createdTime;
}
public void setCreatedTime(long createdTime) {
this.createdTime = createdTime;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Long.hashCode(createdTime);
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false; | if (getClass() != obj.getClass())
return false;
BaseData other = (BaseData) obj;
return createdTime == other.createdTime;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BaseData [createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\BaseData.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
@Override
public int getRevision() {
return revision;
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
// persistent object methods ////////////////////////////////////////////////
@Override
public String getId() { | return name;
}
@Override
public Object getPersistentState() {
return value;
}
@Override
public void setId(String id) {
throw new ActivitiException("only provided id generation allowed for properties");
}
@Override
public int getRevisionNext() {
return revision + 1;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "PropertyEntity[name=" + name + ", value=" + value + "]";
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\PropertyEntity.java | 1 |
请完成以下Java代码 | public void setInfo(final String text)
{
infoLine.setVisible(true);
infoLine.setText(text);
} // setInfo
/**
* Show {@link RecordInfo} dialog
*/
private void showRecordInfo()
{
if (m_dse == null)
{
return;
}
final int adTableId = m_dse.getAdTableId();
final ComposedRecordId recordId = m_dse.getRecordId();
if (adTableId <= 0 || recordId == null)
{ | return;
}
if (!Env.getUserRolePermissions().isShowPreference())
{
return;
}
//
final RecordInfo info = new RecordInfo(SwingUtils.getFrame(this), adTableId, recordId);
AEnv.showCenterScreen(info);
}
public void removeBorders()
{
statusLine.setBorder(BorderFactory.createEmptyBorder());
statusDB.setBorder(BorderFactory.createEmptyBorder());
infoLine.setBorder(BorderFactory.createEmptyBorder());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\StatusBar.java | 1 |
请完成以下Java代码 | public String getSsn() {
return ssn;
}
/**
* Sets the value of the ssn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSsn(String value) {
this.ssn = value;
}
/**
* Gets the value of the nif property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getNif() {
return nif;
}
/**
* Sets the value of the nif property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNif(String value) {
this.nif = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\IvgLawType.java | 1 |
请完成以下Java代码 | public String asString() {
return "messaging.system";
}
},
/**
* Messaging operation.
*/
MESSAGING_OPERATION {
@Override
@NonNull
public String asString() {
return "messaging.operation";
}
},
/**
* Messaging destination name.
*/
MESSAGING_DESTINATION_NAME {
@Override
@NonNull
public String asString() {
return "messaging.destination.name";
}
},
/**
* Messaging destination kind.
*/
MESSAGING_DESTINATION_KIND {
@Override
@NonNull
public String asString() {
return "messaging.destination.kind";
}
}
}
/**
* Default {@link KafkaTemplateObservationConvention} for Kafka template key values.
*
* @author Gary Russell
* @author Christian Mergenthaler
* @author Wang Zhiyang
*
* @since 3.0
*
*/
public static class DefaultKafkaTemplateObservationConvention implements KafkaTemplateObservationConvention {
/**
* A singleton instance of the convention. | */
public static final DefaultKafkaTemplateObservationConvention INSTANCE =
new DefaultKafkaTemplateObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(KafkaRecordSenderContext context) {
return KeyValues.of(
TemplateLowCardinalityTags.BEAN_NAME.withValue(context.getBeanName()),
TemplateLowCardinalityTags.MESSAGING_SYSTEM.withValue("kafka"),
TemplateLowCardinalityTags.MESSAGING_OPERATION.withValue("publish"),
TemplateLowCardinalityTags.MESSAGING_DESTINATION_KIND.withValue("topic"),
TemplateLowCardinalityTags.MESSAGING_DESTINATION_NAME.withValue(context.getDestination()));
}
@Override
public String getContextualName(KafkaRecordSenderContext context) {
return context.getDestination() + " send";
}
@Override
@NonNull
public String getName() {
return "spring.kafka.template";
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaTemplateObservation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Optional<InvoicePaySchedule> getByInvoiceId(@NonNull final InvoiceId invoiceId)
{
return invoicePayScheduleRepository.getByInvoiceId(invoiceId);
}
public void createInvoicePaySchedules(final I_C_Invoice invoice)
{
InvoicePayScheduleCreateCommand.builder()
.invoicePayScheduleRepository(invoicePayScheduleRepository)
.orderPayScheduleService(orderPayScheduleService)
.paymentTermService(paymentTermService)
.invoiceRecord(invoice)
.build()
.execute();
}
public void validateInvoiceBeforeCommit(@NonNull final InvoiceId invoiceId)
{
trxManager.accumulateAndProcessBeforeCommit(
"InvoicePayScheduleService.validateInvoiceBeforeCommit",
Collections.singleton(invoiceId),
invoiceIds -> validateInvoicesNow(ImmutableSet.copyOf(invoiceIds))
);
}
private void validateInvoicesNow(final Set<InvoiceId> invoiceIds)
{ | if (invoiceIds.isEmpty()) {return;}
final ImmutableMap<InvoiceId, I_C_Invoice> invoicesById = Maps.uniqueIndex(
invoiceBL.getByIds(invoiceIds),
invoice -> InvoiceId.ofRepoId(invoice.getC_Invoice_ID())
);
invoicePayScheduleRepository.updateByIds(invoicesById.keySet(), invoicePaySchedule -> {
final I_C_Invoice invoice = invoicesById.get(invoicePaySchedule.getInvoiceId());
final Money grandTotal = invoiceBL.extractGrandTotal(invoice).toMoney();
boolean isValid = invoicePaySchedule.validate(grandTotal);
invoice.setIsPayScheduleValid(isValid);
invoiceBL.save(invoice);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\service\InvoicePayScheduleService.java | 2 |
请完成以下Java代码 | public class PropertiesBasedDataSourceScriptDatabaseInitializer<T extends DatabaseInitializationProperties>
extends DataSourceScriptDatabaseInitializer {
/**
* Create a new {@link PropertiesBasedDataSourceScriptDatabaseInitializer} instance.
* @param dataSource the data source
* @param properties the configuration properties
* @see #getSettings
*/
public PropertiesBasedDataSourceScriptDatabaseInitializer(DataSource dataSource, T properties) {
this(dataSource, properties, Collections.emptyMap());
}
/**
* Create a new {@link PropertiesBasedDataSourceScriptDatabaseInitializer} instance.
* @param dataSource the data source
* @param properties the configuration properties
* @param driverMappings the driver mappings
* @see #getSettings
*/
public PropertiesBasedDataSourceScriptDatabaseInitializer(DataSource dataSource, T properties,
Map<DatabaseDriver, String> driverMappings) {
super(dataSource, getSettings(dataSource, properties, driverMappings));
}
/**
* Adapts {@link DatabaseInitializationProperties configuration properties} to
* {@link DatabaseInitializationSettings} replacing any {@literal @@platform@@}
* placeholders.
* @param dataSource the data source
* @param properties the configuration properties
* @param driverMappings the driver mappings
* @param <T> the {@link DatabaseInitializationProperties} type being used
* @return a new {@link DatabaseInitializationSettings} instance
*/
private static <T extends DatabaseInitializationProperties> DatabaseInitializationSettings getSettings(
DataSource dataSource, T properties, Map<DatabaseDriver, String> driverMappings) {
DatabaseInitializationSettings settings = new DatabaseInitializationSettings(); | settings.setSchemaLocations(resolveSchemaLocations(dataSource, properties, driverMappings));
settings.setMode(properties.getInitializeSchema());
settings.setContinueOnError(properties.isContinueOnError());
return settings;
}
private static <T extends DatabaseInitializationProperties> List<String> resolveSchemaLocations(
DataSource dataSource, T properties, Map<DatabaseDriver, String> driverMappings) {
PlatformPlaceholderDatabaseDriverResolver platformResolver = new PlatformPlaceholderDatabaseDriverResolver();
for (Map.Entry<DatabaseDriver, String> entry : driverMappings.entrySet()) {
platformResolver = platformResolver.withDriverPlatform(entry.getKey(), entry.getValue());
}
if (StringUtils.hasText(properties.getPlatform())) {
return platformResolver.resolveAll(properties.getPlatform(), properties.getSchema());
}
return platformResolver.resolveAll(dataSource, properties.getSchema());
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\init\PropertiesBasedDataSourceScriptDatabaseInitializer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Movie {
@Id
@MovieGeneratedId
private Long id;
private String title;
private String director;
public Movie() {
}
public Movie(Long id, String title, String director) {
this.id = id;
this.title = title;
this.director = director;
}
public Movie(String title, String director) {
this.id = id;
this.title = title;
this.director = director;
}
public Long getId() { | return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
} | repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\customidgenerator\Movie.java | 2 |
请完成以下Java代码 | public int getC_BPartner_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID);
}
@Override
public void setC_BPartner_Representative_ID (final int C_BPartner_Representative_ID)
{
if (C_BPartner_Representative_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Representative_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Representative_ID, C_BPartner_Representative_ID);
}
@Override
public int getC_BPartner_Representative_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Representative_ID);
}
@Override
public void setC_Fiscal_Representation_ID (final int C_Fiscal_Representation_ID)
{
if (C_Fiscal_Representation_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Fiscal_Representation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Fiscal_Representation_ID, C_Fiscal_Representation_ID);
}
@Override
public int getC_Fiscal_Representation_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Fiscal_Representation_ID);
}
@Override
public void setTaxID (final @Nullable java.lang.String TaxID)
{
set_Value (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
}
@Override
public org.compiere.model.I_C_Country getTo_Country()
{
return get_ValueAsPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setTo_Country(final org.compiere.model.I_C_Country To_Country)
{
set_ValueFromPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class, To_Country);
}
@Override
public void setTo_Country_ID (final int To_Country_ID)
{
if (To_Country_ID < 1) | set_Value (COLUMNNAME_To_Country_ID, null);
else
set_Value (COLUMNNAME_To_Country_ID, To_Country_ID);
}
@Override
public int getTo_Country_ID()
{
return get_ValueAsInt(COLUMNNAME_To_Country_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setVATaxID (final java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Fiscal_Representation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getPayWayCode() {
return payWayCode;
}
public void setPayWayCode(String payWayCode) {
this.payWayCode = payWayCode;
} | public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthProgramInitParamVo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<PmsOperatorRole> listOperatorRoleByOperatorId(Long operatorId) {
return pmsOperatorRoleDao.listByOperatorId(operatorId);
}
/**
* 保存操作員信息及其关联的角色.
*
* @param pmsOperator
* .
* @param OperatorRoleStr
* .
*/
public void saveOperator(PmsOperator pmsOperator, String OperatorRoleStr) {
// 保存操作员信息
pmsOperatorDao.insert(pmsOperator);
// 保存角色关联信息
if (StringUtils.isNotBlank(OperatorRoleStr) && OperatorRoleStr.length() > 0) {
saveOrUpdateOperatorRole(pmsOperator.getId(), OperatorRoleStr);
}
}
/**
* 根据角色ID查询用户
*
* @param roleId
* @return
*/
public List<PmsOperator> listOperatorByRoleId(Long roleId) {
return pmsOperatorDao.listByRoleId(roleId);
}
/**
* 修改操作員信息及其关联的角色.
*
* @param pmsOperator
* .
* @param OperatorRoleStr
* .
*/
public void updateOperator(PmsOperator pmsOperator, String OperatorRoleStr) {
pmsOperatorDao.update(pmsOperator);
// 更新角色信息
saveOrUpdateOperatorRole(pmsOperator.getId(), OperatorRoleStr);
}
/**
* 保存用户和角色之间的关联关系
*/
private void saveOrUpdateOperatorRole(Long operatorId, String roleIdsStr) {
// 删除原来的角色与操作员关联
List<PmsOperatorRole> listPmsOperatorRoles = pmsOperatorRoleDao.listByOperatorId(operatorId); | Map<Long, PmsOperatorRole> delMap = new HashMap<Long, PmsOperatorRole>();
for (PmsOperatorRole pmsOperatorRole : listPmsOperatorRoles) {
delMap.put(pmsOperatorRole.getRoleId(), pmsOperatorRole);
}
if (StringUtils.isNotBlank(roleIdsStr)) {
// 创建新的关联
String[] roleIds = roleIdsStr.split(",");
for (int i = 0; i < roleIds.length; i++) {
Long roleId = Long.valueOf(roleIds[i]);
if (delMap.get(roleId) == null) {
PmsOperatorRole pmsOperatorRole = new PmsOperatorRole();
pmsOperatorRole.setOperatorId(operatorId);
pmsOperatorRole.setRoleId(roleId);
pmsOperatorRoleDao.insert(pmsOperatorRole);
} else {
delMap.remove(roleId);
}
}
}
Iterator<Long> iterator = delMap.keySet().iterator();
while (iterator.hasNext()) {
Long roleId = iterator.next();
pmsOperatorRoleDao.deleteByRoleIdAndOperatorId(roleId, operatorId);
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsOperatorRoleServiceImpl.java | 2 |
请完成以下Java代码 | public Set<LogLevel> getSupportedLogLevels() {
return LEVELS.getSupported();
}
@Override
public void setLogLevel(@Nullable String loggerName, @Nullable LogLevel level) {
if (loggerName == null || ROOT_LOGGER_NAME.equals(loggerName)) {
loggerName = "";
}
Logger logger = Logger.getLogger(loggerName);
if (logger != null) {
this.configuredLoggers.add(logger);
logger.setLevel(LEVELS.convertSystemToNative(level));
}
}
@Override
public List<LoggerConfiguration> getLoggerConfigurations() {
List<LoggerConfiguration> result = new ArrayList<>();
Enumeration<String> names = LogManager.getLogManager().getLoggerNames();
while (names.hasMoreElements()) {
result.add(getLoggerConfiguration(names.nextElement()));
}
result.sort(CONFIGURATION_COMPARATOR);
return Collections.unmodifiableList(result);
}
@Override
public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) {
Logger logger = Logger.getLogger(loggerName);
if (logger == null) {
return null;
}
LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel());
LogLevel effectiveLevel = LEVELS.convertNativeToSystem(getEffectiveLevel(logger));
String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() : ROOT_LOGGER_NAME);
Assert.state(effectiveLevel != null, "effectiveLevel must not be null");
return new LoggerConfiguration(name, level, effectiveLevel);
}
private Level getEffectiveLevel(Logger root) {
Logger logger = root;
while (logger.getLevel() == null) {
logger = logger.getParent();
} | return logger.getLevel();
}
@Override
public Runnable getShutdownHandler() {
return () -> LogManager.getLogManager().reset();
}
@Override
public void cleanUp() {
this.configuredLoggers.clear();
}
/**
* {@link LoggingSystemFactory} that returns {@link JavaLoggingSystem} if possible.
*/
@Order(Ordered.LOWEST_PRECEDENCE - 1024)
public static class Factory implements LoggingSystemFactory {
private static final boolean PRESENT = ClassUtils.isPresent("java.util.logging.LogManager",
Factory.class.getClassLoader());
@Override
public @Nullable LoggingSystem getLoggingSystem(ClassLoader classLoader) {
if (PRESENT) {
return new JavaLoggingSystem(classLoader);
}
return null;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\java\JavaLoggingSystem.java | 1 |
请完成以下Java代码 | private List<Object> castToNumericIfPossible(List<Object> values) {
try {
if (values.get(6) != null && NumberUtils.isNumber(values.get(6).toString())) {
Double casted = NumberUtils.createDouble(values.get(6).toString());
List<Object> numeric = Lists.newArrayList();
numeric.addAll(values);
numeric.set(6, null);
numeric.set(8, casted);
castedOk++;
return numeric;
}
} catch (Throwable th) {
castErrors++;
}
processPartitions(values); | return values;
}
private boolean isBlockFinished(String line) {
return StringUtils.isBlank(line) || line.equals("\\.");
}
private boolean isBlockTsStarted(String line) {
return line.startsWith("COPY public.ts_kv (");
}
private boolean isBlockLatestStarted(String line) {
return line.startsWith("COPY public.ts_kv_latest (");
}
} | repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\PgCaMigrator.java | 1 |
请完成以下Java代码 | public Builder verificationUri(String verificationUri) {
this.verificationUri = verificationUri;
return this;
}
/**
* Sets the end-user verification URI that includes the user code.
* @param verificationUriComplete the end-user verification URI that includes the
* user code
* @return the {@link Builder}
*/
public Builder verificationUriComplete(String verificationUriComplete) {
this.verificationUriComplete = verificationUriComplete;
return this;
}
/**
* Sets the lifetime (in seconds) of the device code and user code.
* @param expiresIn the lifetime (in seconds) of the device code and user code
* @return the {@link Builder}
*/
public Builder expiresIn(long expiresIn) {
this.expiresIn = expiresIn;
return this;
}
/**
* Sets the minimum amount of time (in seconds) that the client should wait
* between polling requests to the token endpoint.
* @param interval the minimum amount of time between polling requests
* @return the {@link Builder}
*/
public Builder interval(long interval) {
this.interval = interval;
return this;
}
/**
* Sets the additional parameters returned in the response.
* @param additionalParameters the additional parameters returned in the response
* @return the {@link Builder}
*/
public Builder additionalParameters(Map<String, Object> additionalParameters) {
this.additionalParameters = additionalParameters;
return this; | }
/**
* Builds a new {@link OAuth2DeviceAuthorizationResponse}.
* @return a {@link OAuth2DeviceAuthorizationResponse}
*/
public OAuth2DeviceAuthorizationResponse build() {
Assert.hasText(this.verificationUri, "verificationUri cannot be empty");
Assert.isTrue(this.expiresIn > 0, "expiresIn must be greater than zero");
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plusSeconds(this.expiresIn);
OAuth2DeviceCode deviceCode = new OAuth2DeviceCode(this.deviceCode, issuedAt, expiresAt);
OAuth2UserCode userCode = new OAuth2UserCode(this.userCode, issuedAt, expiresAt);
OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = new OAuth2DeviceAuthorizationResponse();
deviceAuthorizationResponse.deviceCode = deviceCode;
deviceAuthorizationResponse.userCode = userCode;
deviceAuthorizationResponse.verificationUri = this.verificationUri;
deviceAuthorizationResponse.verificationUriComplete = this.verificationUriComplete;
deviceAuthorizationResponse.interval = this.interval;
deviceAuthorizationResponse.additionalParameters = Collections
.unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap()
: this.additionalParameters);
return deviceAuthorizationResponse;
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2DeviceAuthorizationResponse.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonRequestBankAccountUpsertItem
{
@ApiModelProperty(position = 10, allowEmptyValue = false)
@JsonProperty("iban")
String iban;
@ApiModelProperty(position = 20, allowEmptyValue = true)
@JsonProperty("currencyCode")
String currencyCode;
@ApiModelProperty(position = 30, required = false, value = "If not specified but required (e.g. because a new contact is created), then `true` is assumed")
@JsonInclude(Include.NON_NULL)
@JsonProperty("active")
Boolean active;
@ApiModelProperty(position = 40, allowEmptyValue = true)
@JsonProperty("accountName")
String accountName;
@ApiModelProperty(position = 50, allowEmptyValue = true)
@JsonProperty("accountStreet")
String accountStreet;
@ApiModelProperty(position = 60, allowEmptyValue = true)
@JsonProperty("accountZip")
String accountZip;
@ApiModelProperty(position = 70, allowEmptyValue = true)
@JsonProperty("accountCity")
String accountCity;
@ApiModelProperty(position = 80, allowEmptyValue = true)
@JsonProperty("accountCountry")
String accountCountry;
@Setter | @ApiModelProperty(value = "Sync advise about this contact's individual properties.\n" + PARENT_SYNC_ADVISE_DOC)
@JsonInclude(Include.NON_NULL)
SyncAdvise syncAdvise;
@JsonCreator
public JsonRequestBankAccountUpsertItem(
@JsonProperty("iban") @NonNull String iban,
@JsonProperty("currencyCode") @Nullable final String currencyCode,
@JsonProperty("active") @Nullable final Boolean active,
@JsonProperty("accountName") @Nullable final String accountName,
@JsonProperty("accountStreet") @Nullable final String accountStreet,
@JsonProperty("accountZip") @Nullable final String accountZip,
@JsonProperty("accountCity") @Nullable final String accountCity,
@JsonProperty("accountCountry") @Nullable final String accountCountry,
@JsonProperty("syncAdvise") @Nullable final SyncAdvise syncAdvise)
{
this.iban = iban;
this.currencyCode = currencyCode;
this.active = active;
this.accountName = accountName;
this.accountStreet = accountStreet;
this.accountZip = accountZip;
this.accountCity = accountCity;
this.accountCountry = accountCountry;
this.syncAdvise = syncAdvise;
}
public boolean getIsActive()
{
return CoalesceUtil.coalesceNotNull(active, true);
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestBankAccountUpsertItem.java | 2 |
请完成以下Java代码 | public class ErrorEndEventActivityBehavior extends FlowNodeActivityBehavior {
private static final long serialVersionUID = 1L;
protected String errorCode;
protected List<IOParameter> outParameters;
public ErrorEndEventActivityBehavior(String errorCode, List<IOParameter> outParameters) {
this.errorCode = errorCode;
this.outParameters = outParameters;
}
@Override
public void execute(DelegateExecution execution) {
ExpressionManager expressionManager = CommandContextUtil.getProcessEngineConfiguration().getExpressionManager();
Map<String, Object> payload = IOParameterUtil.extractOutVariables(outParameters, execution, expressionManager); | Object errorMessage = payload.remove("errorMessage");
BpmnError error = new BpmnError(errorCode, errorMessage != null ? errorMessage.toString() : null);
if (!payload.isEmpty()) {
error.setAdditionalDataContainer(new VariableContainerWrapper(payload));
}
ErrorPropagation.propagateError(error, execution);
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\ErrorEndEventActivityBehavior.java | 1 |
请完成以下Java代码 | public void setMSV3_Tourabweichung (boolean MSV3_Tourabweichung)
{
set_Value (COLUMNNAME_MSV3_Tourabweichung, Boolean.valueOf(MSV3_Tourabweichung));
}
/** Get Tourabweichung.
@return Tourabweichung */
@Override
public boolean isMSV3_Tourabweichung ()
{
Object oo = get_Value(COLUMNNAME_MSV3_Tourabweichung);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/**
* MSV3_Typ AD_Reference_ID=540823
* Reference name: MSV3_BestellungRueckmeldungTyp
*/
public static final int MSV3_TYP_AD_Reference_ID=540823;
/** Normal = Normal */
public static final String MSV3_TYP_Normal = "Normal";
/** Verbund = Verbund */
public static final String MSV3_TYP_Verbund = "Verbund";
/** Nachlieferung = Nachlieferung */
public static final String MSV3_TYP_Nachlieferung = "Nachlieferung";
/** Dispo = Dispo */
public static final String MSV3_TYP_Dispo = "Dispo";
/** KeineLieferungAberNormalMoeglich = KeineLieferungAberNormalMoeglich */
public static final String MSV3_TYP_KeineLieferungAberNormalMoeglich = "KeineLieferungAberNormalMoeglich"; | /** KeineLieferungAberVerbundMoeglich = KeineLieferungAberVerbundMoeglich */
public static final String MSV3_TYP_KeineLieferungAberVerbundMoeglich = "KeineLieferungAberVerbundMoeglich";
/** KeineLieferungAberNachlieferungMoeglich = KeineLieferungAberNachlieferungMoeglich */
public static final String MSV3_TYP_KeineLieferungAberNachlieferungMoeglich = "KeineLieferungAberNachlieferungMoeglich";
/** KeineLieferungAberDispoMoeglich = KeineLieferungAberDispoMoeglich */
public static final String MSV3_TYP_KeineLieferungAberDispoMoeglich = "KeineLieferungAberDispoMoeglich";
/** NichtLieferbar = NichtLieferbar */
public static final String MSV3_TYP_NichtLieferbar = "NichtLieferbar";
/** Set Typ.
@param MSV3_Typ Typ */
@Override
public void setMSV3_Typ (java.lang.String MSV3_Typ)
{
set_Value (COLUMNNAME_MSV3_Typ, MSV3_Typ);
}
/** Get Typ.
@return Typ */
@Override
public java.lang.String getMSV3_Typ ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_Typ);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAnteil.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
} | public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}
} | repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\model\Movie.java | 1 |
请完成以下Java代码 | public void setName2 (String Name2)
{
set_Value (COLUMNNAME_Name2, Name2);
}
/** Get Name 2.
@return Additional Name
*/
public String getName2 ()
{
return (String)get_Value(COLUMNNAME_Name2);
}
/** Set National Code.
@param NationalCode National Code */
public void setNationalCode (String NationalCode)
{
set_Value (COLUMNNAME_NationalCode, NationalCode);
}
/** Get National Code.
@return National Code */
public String getNationalCode ()
{
return (String)get_Value(COLUMNNAME_NationalCode);
}
/** Set Social Security Code.
@param SSCode Social Security Code */
public void setSSCode (String SSCode)
{ | set_Value (COLUMNNAME_SSCode, SSCode);
}
/** Get Social Security Code.
@return Social Security Code */
public String getSSCode ()
{
return (String)get_Value(COLUMNNAME_SSCode);
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Employee.java | 1 |
请完成以下Java代码 | public class MyCommonsMultipartFile implements MultipartFile {
private final byte[] fileContent;
private final String fileName;
private final String contentType;
// 新增构造方法,支持 FileItem 参数
public MyCommonsMultipartFile(FileItem fileItem) throws IOException {
this.fileName = fileItem.getName();
this.contentType = fileItem.getContentType();
try (InputStream inputStream = fileItem.getInputStream()) {
this.fileContent = inputStream.readAllBytes();
}
}
// 现有构造方法
public MyCommonsMultipartFile(InputStream inputStream, String fileName, String contentType) throws IOException {
this.fileName = fileName;
this.contentType = contentType;
this.fileContent = inputStream.readAllBytes();
}
@Override
public String getName() {
return fileName;
}
@Override
public String getOriginalFilename() {
return fileName;
}
@Override
public String getContentType() {
return contentType;
} | @Override
public boolean isEmpty() {
return fileContent.length == 0;
}
@Override
public long getSize() {
return fileContent.length;
}
@Override
public byte[] getBytes() {
return fileContent;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(fileContent);
}
@Override
public void transferTo(File dest) throws IOException {
try (OutputStream os = new FileOutputStream(dest)) {
os.write(fileContent);
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\MyCommonsMultipartFile.java | 1 |
请完成以下Java代码 | public boolean isFoundGoalRecord()
{
return foundGoal;
}
@Override
public boolean contains(final ITableRecordReference forwardReference)
{
return g.containsVertex(forwardReference);
}
public List<ITableRecordReference> getPath()
{
final List<ITableRecordReference> result = new ArrayList<>();
final AsUndirectedGraph<ITableRecordReference, DefaultEdge> undirectedGraph = new AsUndirectedGraph<>(g);
final List<DefaultEdge> path = DijkstraShortestPath.<ITableRecordReference, DefaultEdge> findPathBetween(
undirectedGraph, start, goal);
if (path == null || path.isEmpty())
{
return ImmutableList.of();
}
result.add(start);
for (final DefaultEdge e : path)
{
final ITableRecordReference edgeSource = undirectedGraph.getEdgeSource(e); | if (!result.contains(edgeSource))
{
result.add(edgeSource);
}
else
{
result.add(undirectedGraph.getEdgeTarget(e));
}
}
return ImmutableList.copyOf(result);
}
/* package */ Graph<ITableRecordReference, DefaultEdge> getGraph()
{
return g;
}
@Override
public String toString()
{
return "FindPathIterateResult [start=" + start + ", goal=" + goal + ", size=" + size + ", foundGoal=" + foundGoal + ", queueItemsToProcess.size()=" + queueItemsToProcess.size() + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\graph\FindPathIterateResult.java | 1 |
请完成以下Java代码 | public class Payment {
private String reference;
private BigDecimal amount;
private Currency currency;
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) { | this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
@Override
public String toString() {
return new StringJoiner(", ", Payment.class.getSimpleName() + "[", "]").add("reference='" + reference + "'")
.add("amount=" + amount)
.add("currency=" + currency)
.toString();
}
} | repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\dlt\Payment.java | 1 |
请完成以下Java代码 | private void setup() {
this.config = HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey));
this.config = config.andCommandKey(HystrixCommandKey.Factory.asKey(key));
this.commandProperties = HystrixCommandProperties.Setter();
this.commandProperties.withExecutionTimeoutInMilliseconds(executionTimeout);
this.commandProperties.withCircuitBreakerSleepWindowInMilliseconds(sleepWindow);
this.threadPoolProperties = HystrixThreadPoolProperties.Setter();
this.threadPoolProperties.withMaxQueueSize(maxThreadCount).withCoreSize(coreThreadCount).withMaxQueueSize(queueCount);
this.config.andCommandPropertiesDefaults(commandProperties);
this.config.andThreadPoolPropertiesDefaults(threadPoolProperties);
}
private static class RemoteServiceCommand extends HystrixCommand<String> {
private final ProceedingJoinPoint joinPoint;
RemoteServiceCommand(final Setter config, final ProceedingJoinPoint joinPoint) { | super(config);
this.joinPoint = joinPoint;
}
@Override
protected String run() throws Exception {
try {
return (String) joinPoint.proceed();
} catch (final Throwable th) {
throw new Exception(th);
}
}
}
} | repos\tutorials-master\hystrix\src\main\java\com\baeldung\hystrix\HystrixAspect.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public Date getCreateTime() {
return createTime;
}
public Date getEndTime() {
return endTime;
}
public Date getRemovalTime() {
return removalTime;
}
public String getIncidentType() {
return incidentType;
}
public String getActivityId() {
return activityId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public String getCauseIncidentId() {
return causeIncidentId;
}
public String getRootCauseIncidentId() {
return rootCauseIncidentId;
}
public String getConfiguration() {
return configuration;
}
public String getHistoryConfiguration() {
return historyConfiguration;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getTenantId() { | return tenantId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public Boolean isOpen() {
return open;
}
public Boolean isDeleted() {
return deleted;
}
public Boolean isResolved() {
return resolved;
}
public String getAnnotation() {
return annotation;
}
public static HistoricIncidentDto fromHistoricIncident(HistoricIncident historicIncident) {
HistoricIncidentDto dto = new HistoricIncidentDto();
dto.id = historicIncident.getId();
dto.processDefinitionKey = historicIncident.getProcessDefinitionKey();
dto.processDefinitionId = historicIncident.getProcessDefinitionId();
dto.processInstanceId = historicIncident.getProcessInstanceId();
dto.executionId = historicIncident.getExecutionId();
dto.createTime = historicIncident.getCreateTime();
dto.endTime = historicIncident.getEndTime();
dto.incidentType = historicIncident.getIncidentType();
dto.failedActivityId = historicIncident.getFailedActivityId();
dto.activityId = historicIncident.getActivityId();
dto.causeIncidentId = historicIncident.getCauseIncidentId();
dto.rootCauseIncidentId = historicIncident.getRootCauseIncidentId();
dto.configuration = historicIncident.getConfiguration();
dto.historyConfiguration = historicIncident.getHistoryConfiguration();
dto.incidentMessage = historicIncident.getIncidentMessage();
dto.open = historicIncident.isOpen();
dto.deleted = historicIncident.isDeleted();
dto.resolved = historicIncident.isResolved();
dto.tenantId = historicIncident.getTenantId();
dto.jobDefinitionId = historicIncident.getJobDefinitionId();
dto.removalTime = historicIncident.getRemovalTime();
dto.rootProcessInstanceId = historicIncident.getRootProcessInstanceId();
dto.annotation = historicIncident.getAnnotation();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIncidentDto.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BPartner_EditableAttribute1_ID (final int C_BPartner_EditableAttribute1_ID)
{
if (C_BPartner_EditableAttribute1_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_EditableAttribute1_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_EditableAttribute1_ID, C_BPartner_EditableAttribute1_ID);
}
@Override
public int getC_BPartner_EditableAttribute1_ID() | {
return get_ValueAsInt(COLUMNNAME_C_BPartner_EditableAttribute1_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_EditableAttribute1.java | 1 |
请完成以下Java代码 | public CamundaBpmRunAuthenticationProperties getAuth() {
return auth;
}
public void setAuth(CamundaBpmRunAuthenticationProperties auth) {
this.auth = auth;
}
public CamundaBpmRunCorsProperty getCors() {
return cors;
}
public void setCors(CamundaBpmRunCorsProperty cors) {
this.cors = cors;
}
public CamundaBpmRunLdapProperties getLdap() {
return ldap;
}
public void setLdap(CamundaBpmRunLdapProperties ldap) {
this.ldap = ldap;
}
public CamundaBpmRunAdministratorAuthorizationProperties getAdminAuth() {
return adminAuth;
}
public void setAdminAuth(CamundaBpmRunAdministratorAuthorizationProperties adminAuth) {
this.adminAuth = adminAuth;
}
public List<CamundaBpmRunProcessEnginePluginProperty> getProcessEnginePlugins() {
return processEnginePlugins;
}
public void setProcessEnginePlugins(List<CamundaBpmRunProcessEnginePluginProperty> processEnginePlugins) {
this.processEnginePlugins = processEnginePlugins;
} | public CamundaBpmRunRestProperties getRest() {
return rest;
}
public void setRest(CamundaBpmRunRestProperties rest) {
this.rest = rest;
}
public CamundaBpmRunDeploymentProperties getDeployment() {
return deployment;
}
public void setDeployment(CamundaBpmRunDeploymentProperties deployment) {
this.deployment = deployment;
}
@Override
public String toString() {
return "CamundaBpmRunProperties [" +
"auth=" + auth +
", cors=" + cors +
", ldap=" + ldap +
", adminAuth=" + adminAuth +
", plugins=" + processEnginePlugins +
", rest=" + rest +
", deployment=" + deployment +
"]";
}
} | repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Class<?> getObjectType() {
return AuthenticationManager.class;
}
public void setEraseCredentialsAfterAuthentication(boolean eraseCredentialsAfterAuthentication) {
this.eraseCredentialsAfterAuthentication = eraseCredentialsAfterAuthentication;
}
public void setAuthenticationEventPublisher(AuthenticationEventPublisher authenticationEventPublisher) {
this.authenticationEventPublisher = authenticationEventPublisher;
}
public void setObservationRegistry(ObservationRegistry observationRegistry) {
this.observationRegistry = observationRegistry;
}
}
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
public static final class FilterChainDecoratorFactory
implements FactoryBean<FilterChainProxy.FilterChainDecorator> {
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
@Override
public FilterChainProxy.FilterChainDecorator getObject() throws Exception { | if (this.observationRegistry.isNoop()) {
return new FilterChainProxy.VirtualFilterChainDecorator();
}
return new ObservationFilterChainDecorator(this.observationRegistry);
}
@Override
public Class<?> getObjectType() {
return FilterChainProxy.FilterChainDecorator.class;
}
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\HttpSecurityBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public class PORelationException extends AdempiereException
{
public static PORelationException throwWrongKeyColumnCount(final String tableName, final Collection<String> allKeyColumnNames)
{
final Object[] msgParams = new Object[] { tableName, allKeyColumnNames.size() };
throw new PORelationException(MSG_ERR_KEY_COLUMNS_2P, msgParams);
}
public static PORelationException throwMissingWindowId(final String referenceName, final String tableName, final boolean isSOTrx)
{
final Object[] msgParams = { referenceName, tableName, DisplayType.toBooleanString(isSOTrx) };
throw new PORelationException(MSG_ERR_WINDOW_3P, msgParams);
}
/**
* Message indicates that a po has more or less than one key columns.
* <ul>
* <li>Param 1: the po (toString)</li>
* <li>Param 2: the number of key columns</li>
* </ul> | */
private static final AdMessageKey MSG_ERR_KEY_COLUMNS_2P = AdMessageKey.of("MRelationType_Err_KeyColumns_2P");
/**
* Message indicates that neither the reference nor the table have an
* AD_Window_ID set.
* <ul>
* <li>Param 1: The AD_Reference's name</li>
* <li>Param 2: The Table name</li>
* <li>Param 3: Whether we are in the ctx of a SO (Y or N)</li>
* </ul>
*/
private static final AdMessageKey MSG_ERR_WINDOW_3P = AdMessageKey.of("MRelationType_Err_Window_3P");
private PORelationException(final AdMessageKey adMsg, final Object... msgParams)
{
super(adMsg, msgParams);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\PORelationException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addAllocatedAmounts(@NonNull final AllocationAmounts amounts)
{
amountsAllocated = amountsAllocated.add(amounts);
amountsToAllocate = amountsToAllocate.subtract(amounts);
}
public void moveRemainingOpenAmtToDiscount()
{
amountsToAllocate = amountsToAllocate.movePayAmtToDiscount();
}
public void moveRemainingOpenAmtToWriteOff()
{
amountsToAllocate = amountsToAllocate.movePayAmtToWriteOff();
}
public Money computeProjectedOverUnderAmt(@NonNull final AllocationAmounts amountsToAllocate)
{
return computeOpenAmtRemainingToAllocate().subtract(amountsToAllocate.getTotalAmt());
}
@NonNull
private Money computeOpenAmtRemainingToAllocate()
{
return openAmtInitial.subtract(amountsAllocated.getTotalAmt());
}
@NonNull
public Money getTotalAllocatedAmount()
{ | return amountsAllocated.getTotalAmt();
}
public boolean isFullyAllocated()
{
return amountsToAllocate.getTotalAmt().isZero();
}
public boolean isARC()
{
return isCreditMemo() && getSoTrx().isSales();
}
public boolean isAPI()
{
return !isCreditMemo() && getSoTrx().isPurchase();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PayableDocument.java | 2 |
请完成以下Java代码 | public RawMaterialsIssue getRawMaterialsIssueAssumingNotNull()
{
if (rawMaterialsIssue == null)
{
throw new AdempiereException("Not a raw materials issuing activity");
}
return rawMaterialsIssue;
}
public FinishedGoodsReceive getFinishedGoodsReceiveAssumingNotNull()
{
if (finishedGoodsReceive == null)
{
throw new AdempiereException("Not a material receiving activity");
}
return finishedGoodsReceive;
}
public boolean containsRawMaterialsIssueStep(final PPOrderIssueScheduleId issueScheduleId)
{
return rawMaterialsIssue != null && rawMaterialsIssue.containsRawMaterialsIssueStep(issueScheduleId);
}
public ManufacturingJobActivity withChangedRawMaterialsIssueStep(
@NonNull final PPOrderIssueScheduleId issueScheduleId,
@NonNull UnaryOperator<RawMaterialsIssueStep> mapper)
{
if (rawMaterialsIssue != null)
{
return withRawMaterialsIssue(rawMaterialsIssue.withChangedRawMaterialsIssueStep(issueScheduleId, mapper));
}
else
{
return this;
}
}
public ManufacturingJobActivity withRawMaterialsIssue(@Nullable RawMaterialsIssue rawMaterialsIssue)
{
return Objects.equals(this.rawMaterialsIssue, rawMaterialsIssue) ? this : toBuilder().rawMaterialsIssue(rawMaterialsIssue).build(); | }
public ManufacturingJobActivity withChangedReceiveLine(
@NonNull final FinishedGoodsReceiveLineId id,
@NonNull UnaryOperator<FinishedGoodsReceiveLine> mapper)
{
if (finishedGoodsReceive != null)
{
return withFinishedGoodsReceive(finishedGoodsReceive.withChangedReceiveLine(id, mapper));
}
else
{
return this;
}
}
public ManufacturingJobActivity withFinishedGoodsReceive(@Nullable FinishedGoodsReceive finishedGoodsReceive)
{
return Objects.equals(this.finishedGoodsReceive, finishedGoodsReceive) ? this : toBuilder().finishedGoodsReceive(finishedGoodsReceive).build();
}
@NonNull
public ManufacturingJobActivity withChangedRawMaterialsIssue(@NonNull final UnaryOperator<RawMaterialsIssue> mapper)
{
if (rawMaterialsIssue != null)
{
return withRawMaterialsIssue(mapper.apply(rawMaterialsIssue));
}
else
{
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobActivity.java | 1 |
请完成以下Java代码 | public class JpaApiKeyDao extends JpaAbstractDao<ApiKeyEntity, ApiKey> implements ApiKeyDao {
@Autowired
private ApiKeyRepository apiKeyRepository;
@Override
public ApiKey findByValue(String value) {
return DaoUtil.getData(apiKeyRepository.findByValue(value));
}
@Override
public Set<String> deleteByTenantId(TenantId tenantId) {
return apiKeyRepository.deleteByTenantId(tenantId.getId());
}
@Override
public Set<String> deleteByUserId(TenantId tenantId, UserId userId) {
return apiKeyRepository.deleteByUserId(tenantId.getId(), userId.getId());
}
@Override
public int deleteAllByExpirationTimeBefore(long ts) {
return apiKeyRepository.deleteAllByExpirationTimeBefore(ts);
} | @Override
protected Class<ApiKeyEntity> getEntityClass() {
return ApiKeyEntity.class;
}
@Override
protected JpaRepository<ApiKeyEntity, UUID> getRepository() {
return apiKeyRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.API_KEY;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\pat\JpaApiKeyDao.java | 1 |
请完成以下Java代码 | /* package */class HandlingUnitHUDocumentLine extends AbstractHUDocumentLine
{
private final I_M_HU_Item item;
public HandlingUnitHUDocumentLine(final I_M_HU_Item item, final IProductStorage storage)
{
super(storage, item);
Check.assumeNotNull(item, "item not null");
this.item = item;
}
@Override
public IHUAllocations getHUAllocations()
{ | throw new UnsupportedOperationException("not implemented");
}
@Override
public I_M_HU_Item getInnerHUItem()
{
return item;
}
@Override
public int getC_BPartner_Location_ID()
{
return -1; // N/A
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\HandlingUnitHUDocumentLine.java | 1 |
请完成以下Java代码 | public Optional<IDocumentLocationAdapter> getDocumentLocationAdapterIfHandled(final Object record)
{
return toInOut(record).map(InOutDocumentLocationAdapterFactory::locationAdapter);
}
@Override
public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(final Object record)
{
return Optional.empty();
}
@Override
public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(final Object record)
{
return toInOut(record).map(InOutDocumentLocationAdapterFactory::deliveryLocationAdapter); | }
@Override
public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(final Object record)
{
return Optional.empty();
}
private static Optional<I_M_InOut> toInOut(final Object record)
{
return InterfaceWrapperHelper.isInstanceOf(record, I_M_InOut.class)
? Optional.of(InterfaceWrapperHelper.create(record, I_M_InOut.class))
: Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\InOutDocumentLocationAdapterFactory.java | 1 |
请完成以下Java代码 | default <T> Stream<T> streamModelsByIds(@NonNull final DocumentIdsSelection rowIds, @NonNull final Class<T> modelClass)
{
return retrieveModelsByIds(rowIds, modelClass).stream();
}
/**
* @return a stream which contains only the {@link IViewRow}s which given <code>rowId</code>s.
* If a {@link IViewRow} was not found for given ID, this method simply ignores it.
*/
Stream<? extends IViewRow> streamByIds(DocumentIdsSelection rowIds);
default Stream<? extends IViewRow> streamByIds(DocumentIdsSelection rowIds, QueryLimit suggestedLimit)
{
return streamByIds(rowIds);
}
default Stream<? extends IViewRow> streamByIds(DocumentIdsSelection rowIds, DocumentQueryOrderByList orderBys, QueryLimit suggestedLimit)
{
return streamByIds(rowIds);
}
/**
* Notify the view that given record(s) has changed.
*/ | void notifyRecordsChanged(TableRecordReferenceSet recordRefs, boolean watchedByFrontend);
/**
* @return actions which were registered particularly for this view instance
*/
default ViewActionDescriptorsList getActions()
{
return ViewActionDescriptorsList.EMPTY;
}
default boolean isConsiderTableRelatedProcessDescriptors(@NonNull final ProcessHandlerType processHandlerType, @NonNull final DocumentIdsSelection selectedRowIds)
{
return true;
}
default List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return ImmutableList.of();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IView.java | 1 |
请完成以下Java代码 | protected Boolean getAllowNegativeCapacityOverride(final IAllocationRequest request)
{
if (getCapacity().isInfiniteCapacity()) // 08443: For infinite capacity, disallow negative capacity overrides ()
{
return false;
}
else if (isConsiderForceQtyAllocationFromRequest() && request.isForceQtyAllocation())
{
return true;
}
else
{
return isAllowNegativeStorage();
}
}
private boolean isEligible(final IAllocationRequest request)
{
// NOTE: don't throw exception but just return false,
// because we have the case where are multiple storages in a pool and each of them are asked if they can fullfill a given request
return Objects.equals(request.getProductId(), getProductId());
}
protected final BigDecimal convertToStorageUOM(final BigDecimal qty, final I_C_UOM uom)
{
Check.assumeNotNull(qty, "qty not null");
Check.assumeNotNull(uom, "uom not null");
final ProductId productId = getProductId();
final I_C_UOM storageUOM = getC_UOM();
final BigDecimal qtyConverted = Services.get(IUOMConversionBL.class)
.convertQty(productId, qty, uom, storageUOM); | Check.assumeNotNull(qtyConverted,
"qtyConverted not null (Qty={}, FromUOM={}, ToUOM={}, Product={}",
qty, uom, storageUOM);
return qtyConverted;
}
@Override
public boolean isEmpty()
{
return getQty().isZero();
}
public boolean isFull()
{
final BigDecimal qtyFree = getQtyFree();
return qtyFree.signum() == 0;
}
@Override
public final void markStaled()
{
beforeMarkingStalled();
_capacity = null;
}
/**
* This method is called when {@link #markStaled()} is executed, right before resetting the status.
*
* NOTE: To be implemented by extending classes.
*/
protected void beforeMarkingStalled()
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\AbstractProductStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MaterialCockpitRowLookups
{
@NonNull private final LookupDataSource uomLookup;
@NonNull private final LookupDataSource bpartnerLookup;
@NonNull private final LookupDataSource productLookup;
@Autowired
public MaterialCockpitRowLookups(final @NonNull LookupDataSourceFactory lookupFactory)
{
this.uomLookup = lookupFactory.searchInTableLookup(I_C_UOM.Table_Name);
this.bpartnerLookup = lookupFactory.searchInTableLookup(I_C_BPartner.Table_Name);
this.productLookup = lookupFactory.searchInTableLookup(I_M_Product.Table_Name);
}
@VisibleForTesting
@Builder
private MaterialCockpitRowLookups(
@NonNull final LookupDataSource uomLookup,
@NonNull final LookupDataSource bpartnerLookup, | @NonNull final LookupDataSource productLookup)
{
this.uomLookup = uomLookup;
this.bpartnerLookup = bpartnerLookup;
this.productLookup = productLookup;
}
@Nullable
public LookupValue lookupUOMById(@Nullable final UomId uomId) {return uomLookup.findById(uomId);}
@Nullable
public LookupValue lookupBPartnerById(@Nullable final BPartnerId bpartnerId) {return bpartnerLookup.findById(bpartnerId);}
@Nullable
public LookupValue lookupProductById(@Nullable final ProductId productId) {return productLookup.findById(productId);}
public DocumentZoomIntoInfo getZoomInto(@Nullable final ProductId productId) {return productLookup.getDocumentZoomInto(ProductId.toRepoId(productId));}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRowLookups.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private PhonecallSchemaVersionRange createPhonecallSchemaVersionRange(
final PhonecallSchemaVersion schemaVersion,
final LocalDate startDate,
final LocalDate endDate)
{
return PhonecallSchemaVersionRange.builder()
.phonecallSchemaVersion(schemaVersion)
.startDate(startDate)
.endDate(endDate)
.dateSequenceGenerator(createDateSequenceGenerator(schemaVersion, startDate, endDate))
.build();
}
public DateSequenceGenerator createDateSequenceGenerator(
@NonNull final PhonecallSchemaVersion schemaVersion,
@NonNull final LocalDate validFrom,
@NonNull final LocalDate validTo)
{
final Frequency frequency = schemaVersion.getFrequency();
if (frequency == null)
{
return null;
}
final OnNonBussinessDay onNonBusinessDay = schemaRepo.extractOnNonBussinessDayOrNull(schemaVersion);
return DateSequenceGenerator.builder()
.dateFrom(validFrom)
.dateTo(validTo)
.shifter(createDateShifter(frequency, onNonBusinessDay))
.frequency(frequency)
.build();
}
private static IDateShifter createDateShifter(final Frequency frequency, final OnNonBussinessDay onNonBusinessDay)
{ | final IBusinessDayMatcher businessDayMatcher = createBusinessDayMatcher(frequency, onNonBusinessDay);
return BusinessDayShifter.builder()
.businessDayMatcher(businessDayMatcher)
.onNonBussinessDay(onNonBusinessDay != null ? onNonBusinessDay : OnNonBussinessDay.Cancel)
.build();
}
public static IBusinessDayMatcher createBusinessDayMatcher(final Frequency frequency, final OnNonBussinessDay onNonBusinessDay)
{
final ICalendarBL calendarBL = Services.get(ICalendarBL.class);
//
// If user explicitly asked for a set of week days, don't consider them non-business days by default
if (frequency.isWeekly()
&& frequency.isOnlySomeDaysOfTheWeek()
&& onNonBusinessDay == null)
{
return calendarBL.createBusinessDayMatcherExcluding(frequency.getOnlyDaysOfWeek());
}
else
{
return calendarBL.createBusinessDayMatcherExcluding(ImmutableSet.of());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\service\PhonecallScheduleService.java | 2 |
请完成以下Java代码 | protected void addToOverlaps(Intervalable interval, List<Intervalable> overlaps, List<Intervalable> newOverlaps)
{
for (Intervalable currentInterval : newOverlaps)
{
if (!currentInterval.equals(interval))
{
overlaps.add(currentInterval);
}
}
}
/**
* 往左边寻找重叠
* @param interval
* @return
*/
protected List<Intervalable> checkForOverlapsToTheLeft(Intervalable interval)
{
return checkForOverlaps(interval, Direction.LEFT);
}
/**
* 往右边寻找重叠
* @param interval
* @return
*/
protected List<Intervalable> checkForOverlapsToTheRight(Intervalable interval)
{
return checkForOverlaps(interval, Direction.RIGHT);
}
/**
* 寻找重叠
* @param interval 一个区间,与该区间重叠
* @param direction 方向,表明重叠区间在interval的左边还是右边
* @return
*/
protected List<Intervalable> checkForOverlaps(Intervalable interval, Direction direction)
{
List<Intervalable> overlaps = new ArrayList<Intervalable>();
for (Intervalable currentInterval : this.intervals)
{
switch (direction)
{
case LEFT:
if (currentInterval.getStart() <= interval.getEnd())
{
overlaps.add(currentInterval);
}
break;
case RIGHT: | if (currentInterval.getEnd() >= interval.getStart())
{
overlaps.add(currentInterval);
}
break;
}
}
return overlaps;
}
/**
* 是对IntervalNode.findOverlaps(Intervalable)的一个包装,防止NPE
* @see IntervalNode#findOverlaps(Intervalable)
* @param node
* @param interval
* @return
*/
protected static List<Intervalable> findOverlappingRanges(IntervalNode node, Intervalable interval)
{
if (node != null)
{
return node.findOverlaps(interval);
}
return Collections.emptyList();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\interval\IntervalNode.java | 1 |
请完成以下Java代码 | public Iterator<Entry<String, Object>> iterator() {
return new DecoratingEntryIterator(delegate.entrySet().iterator());
}
@Override
public int size() {
return delegate.size();
}
};
}
private class DecoratingEntryIterator implements Iterator<Entry<String, Object>> {
private final Iterator<Entry<String, Object>> delegate;
DecoratingEntryIterator(Iterator<Entry<String, Object>> delegate) {
this.delegate = delegate;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public Entry<String, Object> next() {
Entry<String, Object> entry = delegate.next();
return new AbstractMap.SimpleEntry<>(entry.getKey(), cachingResolver.resolveProperty(entry.getKey()));
}
}
@Override
public void forEach(BiConsumer<? super String, ? super Object> action) {
delegate.forEach((k, v) -> action.accept(k, cachingResolver.resolveProperty(k))); | }
private class DecoratingEntryValueIterator implements Iterator<Object> {
private final Iterator<Entry<String, Object>> entryIterator;
DecoratingEntryValueIterator(Iterator<Entry<String, Object>> entryIterator) {
this.entryIterator = entryIterator;
}
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public Object next() {
Entry<String, Object> entry = entryIterator.next();
return cachingResolver.resolveProperty(entry.getKey());
}
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\EncryptableMapWrapper.java | 1 |
请完成以下Java代码 | public void setIsReplicated (boolean IsReplicated)
{
set_Value (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated));
}
/** Get Replicated.
@return The data is successfully replicated
*/
public boolean isReplicated ()
{
Object oo = get_Value(COLUMNNAME_IsReplicated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Process Message.
@param P_Msg Process Message */
public void setP_Msg (String P_Msg)
{
set_Value (COLUMNNAME_P_Msg, P_Msg);
}
/** Get Process Message.
@return Process Message */
public String getP_Msg ()
{
return (String)get_Value(COLUMNNAME_P_Msg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Log.java | 1 |
请完成以下Java代码 | public int countNotificationTemplatesByTenantIdAndNotificationTypes(TenantId tenantId, Collection<NotificationType> notificationTypes) {
return notificationTemplateDao.countByTenantIdAndNotificationTypes(tenantId, notificationTypes);
}
@Override
public void deleteNotificationTemplateById(TenantId tenantId, NotificationTemplateId id) {
deleteEntity(tenantId, id, false);
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
if (!force) {
if (notificationRequestDao.existsByTenantIdAndStatusAndTemplateId(tenantId, NotificationRequestStatus.SCHEDULED, (NotificationTemplateId) id)) {
throw new IllegalArgumentException("Notification template is referenced by scheduled notification request");
}
if (tenantId.isSysTenantId()) {
NotificationTemplate notificationTemplate = findNotificationTemplateById(tenantId, (NotificationTemplateId) id);
if (notificationTemplate.getNotificationType().isSystem()) {
throw new IllegalArgumentException("System notification template cannot be deleted");
}
}
}
try {
notificationTemplateDao.removeById(tenantId, id.getId());
} catch (Exception e) {
checkConstraintViolation(e, Map.of(
"fk_notification_rule_template_id", "Notification template is referenced by notification rule"
));
throw e;
}
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build()); | }
@Override
public void deleteNotificationTemplatesByTenantId(TenantId tenantId) {
notificationTemplateDao.removeByTenantId(tenantId);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
deleteNotificationTemplatesByTenantId(tenantId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findNotificationTemplateById(tenantId, new NotificationTemplateId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(notificationTemplateDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TEMPLATE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationTemplateService.java | 1 |
请完成以下Java代码 | public String getBatchId() {
return batchId;
}
public boolean isCreationLog() {
return creationLog;
}
public boolean isFailureLog() {
return failureLog;
}
public boolean isSuccessLog() {
return successLog;
}
public boolean isDeletionLog() {
return deletionLog;
}
public static HistoricJobLogDto fromHistoricJobLog(HistoricJobLog historicJobLog) {
HistoricJobLogDto result = new HistoricJobLogDto();
result.id = historicJobLog.getId();
result.timestamp = historicJobLog.getTimestamp();
result.removalTime = historicJobLog.getRemovalTime();
result.jobId = historicJobLog.getJobId();
result.jobDueDate = historicJobLog.getJobDueDate();
result.jobRetries = historicJobLog.getJobRetries();
result.jobPriority = historicJobLog.getJobPriority();
result.jobExceptionMessage = historicJobLog.getJobExceptionMessage(); | result.jobDefinitionId = historicJobLog.getJobDefinitionId();
result.jobDefinitionType = historicJobLog.getJobDefinitionType();
result.jobDefinitionConfiguration = historicJobLog.getJobDefinitionConfiguration();
result.activityId = historicJobLog.getActivityId();
result.failedActivityId = historicJobLog.getFailedActivityId();
result.executionId = historicJobLog.getExecutionId();
result.processInstanceId = historicJobLog.getProcessInstanceId();
result.processDefinitionId = historicJobLog.getProcessDefinitionId();
result.processDefinitionKey = historicJobLog.getProcessDefinitionKey();
result.deploymentId = historicJobLog.getDeploymentId();
result.tenantId = historicJobLog.getTenantId();
result.hostname = historicJobLog.getHostname();
result.rootProcessInstanceId = historicJobLog.getRootProcessInstanceId();
result.batchId = historicJobLog.getBatchId();
result.creationLog = historicJobLog.isCreationLog();
result.failureLog = historicJobLog.isFailureLog();
result.successLog = historicJobLog.isSuccessLog();
result.deletionLog = historicJobLog.isDeletionLog();
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricJobLogDto.java | 1 |
请完成以下Java代码 | private void addHUProductStorage(final IHUProductStorage huProductStorage)
{
pickFromHUs.add(PickFromHU.builder()
.huId(huProductStorage.getHuId())
.qtyToPick(huProductStorage.getQty())
.qtyToPickInStockingUOM(huProductStorage.getQtyInStockingUOM())
.build());
}
public Quantity getQtyInSourceUOM()
{
return pickFromHUs.stream()
.map(PickFromHU::getQtyToPick)
.reduce(Quantity::add)
.orElseThrow(() -> new AdempiereException("No HUs"));
}
public Quantity getQtyInStockingUOM()
{
return pickFromHUs.stream()
.map(PickFromHU::getQtyToPickInStockingUOM)
.reduce(Quantity::add)
.orElseThrow(() -> new AdempiereException("No HUs"));
}
public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product()
{
return piItemProduct;
}
public List<PickFromHU> getPickFromHUs()
{
return pickFromHUs;
}
public String getDescription()
{
final StringBuilder description = new StringBuilder();
for (final PickFromHU pickFromHU : pickFromHUs)
{
final String huValue = String.valueOf(pickFromHU.getHuId().getRepoId());
if (description.length() > 0)
{
description.append(", ");
}
description.append(huValue); | }
description.insert(0, Services.get(IMsgBL.class).translate(Env.getCtx(), "M_HU_ID") + ": ");
return description.toString();
}
public LotNumberQuarantine getLotNumberQuarantine()
{
return lotNoQuarantine;
}
public Map<I_M_Attribute, Object> getAttributes()
{
return attributes;
}
//
// ---------------------------------------------------------------
//
@Value
@Builder
public static class PickFromHU
{
@NonNull HuId huId;
@NonNull Quantity qtyToPick;
@NonNull Quantity qtyToPickInStockingUOM;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\producer\DDOrderLineCandidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void forwardRpcRequestToDeviceActor(ToDeviceRpcRequest request, Consumer<FromDeviceRpcResponse> responseConsumer) {
log.trace("[{}][{}] Processing local rpc call to device actor [{}]", request.getTenantId(), request.getId(), request.getDeviceId());
UUID requestId = request.getId();
toDeviceRpcRequests.put(requestId, responseConsumer);
sendRpcRequestToDevice(request);
scheduleTimeout(request, requestId);
}
private void sendRpcRequestToDevice(ToDeviceRpcRequest msg) {
TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, msg.getTenantId(), msg.getDeviceId());
ToDeviceRpcRequestActorMsg rpcMsg = new ToDeviceRpcRequestActorMsg(serviceId, msg);
if (tpi.isMyPartition()) {
log.trace("[{}] Forwarding msg {} to device actor!", msg.getDeviceId(), msg);
if (tbCoreRpcService.isPresent()) {
tbCoreRpcService.get().forwardRpcRequestToDeviceActor(rpcMsg);
} else {
log.warn("Failed to find tbCoreRpcService for local service. Possible duplication of serviceIds.");
}
} else {
log.trace("[{}] Forwarding msg {} to queue actor!", msg.getDeviceId(), msg);
clusterService.pushMsgToCore(rpcMsg, null);
}
}
private void sendRpcResponseToTbCore(String originServiceId, FromDeviceRpcResponse response) {
if (serviceId.equals(originServiceId)) {
if (tbCoreRpcService.isPresent()) {
tbCoreRpcService.get().processRpcResponseFromRuleEngine(response); | } else {
log.warn("Failed to find tbCoreRpcService for local service. Possible duplication of serviceIds.");
}
} else {
clusterService.pushNotificationToCore(originServiceId, response, null);
}
}
private void scheduleTimeout(ToDeviceRpcRequest request, UUID requestId) {
long timeout = Math.max(0, request.getExpirationTime() - System.currentTimeMillis()) + TimeUnit.SECONDS.toMillis(1);
log.trace("[{}] processing the request: [{}]", this.hashCode(), requestId);
scheduler.schedule(() -> {
log.trace("[{}] timeout the request: [{}]", this.hashCode(), requestId);
Consumer<FromDeviceRpcResponse> consumer = toDeviceRpcRequests.remove(requestId);
if (consumer != null) {
scheduler.submit(() -> consumer.accept(new FromDeviceRpcResponse(requestId, null, RpcError.TIMEOUT)));
}
}, timeout, TimeUnit.MILLISECONDS);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\rpc\DefaultTbRuleEngineRpcService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private CandidateSaveResult createHeaderCandidate(@NonNull final PPOrderCreatedEvent ppOrderEvent)
{
final PPOrder ppOrder = ppOrderEvent.getPpOrder();
final Candidate.CandidateBuilder builder = Candidate.builderForClientAndOrgId(ppOrder.getPpOrderData().getClientAndOrgId());
retrieveDemandDetail(ppOrder.getPpOrderData())
.ifPresent(builder::additionalDemandDetail);
final Candidate headerCandidate = builder
.type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PRODUCTION)
.businessCaseDetail(createProductionDetailForPPOrder(ppOrderEvent))
.materialDescriptor(createMaterialDescriptorForPPOrder(ppOrder))
// .groupId(null) // will be set after save
.build();
return candidateChangeService.onCandidateNewOrChange(headerCandidate, OnNewOrChangeAdvise.attemptUpdate(false));
}
@NonNull
private MaterialDescriptor createMaterialDescriptorForPPOrder(@NonNull final PPOrder ppOrder)
{
return MaterialDescriptor.builder()
.date(ppOrder.getPpOrderData().getDatePromised())
.productDescriptor(ppOrder.getPpOrderData().getProductDescriptor())
.quantity(ppOrder.getPpOrderData().getQtyOpen())
.warehouseId(ppOrder.getPpOrderData().getWarehouseId())
.build();
}
@NonNull
private ProductionDetail createProductionDetailForPPOrder(
@NonNull final PPOrderCreatedEvent ppOrderEvent)
{
final PPOrder ppOrder = ppOrderEvent.getPpOrder();
return ProductionDetail.builder()
.advised(Flag.FALSE_DONT_UPDATE)
.pickDirectlyIfFeasible(Flag.of(ppOrderEvent.isDirectlyPickIfFeasible()))
.qty(ppOrder.getPpOrderData().getQtyRequired())
.plantId(ppOrder.getPpOrderData().getPlantId())
.workstationId(ppOrder.getPpOrderData().getWorkstationId())
.productPlanningId(ppOrder.getPpOrderData().getProductPlanningId())
.ppOrderRef(PPOrderRef.ofPPOrderId(ppOrder.getPpOrderId()))
.ppOrderDocStatus(ppOrder.getDocStatus()) | .build();
}
@NonNull
private Optional<DemandDetail> retrieveDemandDetail(@NonNull final PPOrderData ppOrderData)
{
if (ppOrderData.getShipmentScheduleId() <= 0)
{
return Optional.empty();
}
final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery.
ofShipmentScheduleId(ppOrderData.getShipmentScheduleId());
final MaterialDescriptorQuery materialDescriptorQuery = MaterialDescriptorQuery.builder()
.productId(ppOrderData.getProductDescriptor().getProductId())
.warehouseId(ppOrderData.getWarehouseId())
.build();
final CandidatesQuery candidatesQuery = CandidatesQuery.builder()
.type(CandidateType.DEMAND)
.materialDescriptorQuery(materialDescriptorQuery)
.demandDetailsQuery(demandDetailsQuery)
.build();
return candidateRepositoryRetrieval.retrieveLatestMatch(candidatesQuery)
.map(Candidate::getDemandDetail);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\pporder\PPOrderCreatedHandler.java | 2 |
请完成以下Java代码 | public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {}
protected String getStencilId(BaseElement baseElement) {
return STENCIL_TASK_DECISION;
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
ServiceTask serviceTask = new ServiceTask();
serviceTask.setType(ServiceTask.DMN_TASK);
JsonNode decisionTableReferenceNode = getProperty(PROPERTY_DECISIONTABLE_REFERENCE, elementNode);
if (
decisionTableReferenceNode != null &&
decisionTableReferenceNode.has("id") &&
!(decisionTableReferenceNode.get("id").isNull())
) {
String decisionTableId = decisionTableReferenceNode.get("id").asText();
if (decisionTableMap != null) {
String decisionTableKey = decisionTableMap.get(decisionTableId);
FieldExtension decisionTableKeyField = new FieldExtension();
decisionTableKeyField.setFieldName(PROPERTY_DECISIONTABLE_REFERENCE_KEY);
decisionTableKeyField.setStringValue(decisionTableKey);
serviceTask.getFieldExtensions().add(decisionTableKeyField);
}
}
return serviceTask; | }
@Override
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {}
@Override
public void setDecisionTableMap(Map<String, String> decisionTableMap) {
this.decisionTableMap = decisionTableMap;
}
protected void addExtensionAttributeToExtension(ExtensionElement element, String attributeName, String value) {
ExtensionAttribute extensionAttribute = new ExtensionAttribute(NAMESPACE, attributeName);
extensionAttribute.setNamespacePrefix("modeler");
extensionAttribute.setValue(value);
element.addAttribute(extensionAttribute);
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\DecisionTaskJsonConverter.java | 1 |
请完成以下Java代码 | public void onError(Throwable e) {
log.trace("Failed to process certificate chain: {}", certificateChain, e);
latch.countDown();
}
});
latch.await(10, TimeUnit.SECONDS);
if (!clientDeviceCertValue.equals(credentialsBodyHolder[0])) {
log.debug("Failed to find credentials for device certificate chain: {}", chain);
if (chain.length == 1) {
throw new CertificateException("Invalid Device Certificate");
} else {
throw new CertificateException("Invalid Chain of X509 Certificates");
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private boolean validateCertificateChain(X509Certificate[] chain) { | try {
if (chain.length > 1) {
X509Certificate leafCert = chain[0];
for (int i = 1; i < chain.length; i++) {
X509Certificate intermediateCert = chain[i];
leafCert.verify(intermediateCert.getPublicKey());
leafCert = intermediateCert;
}
}
return true;
} catch (Exception e) {
return false;
}
}
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\MqttSslHandlerProvider.java | 1 |
请完成以下Java代码 | public title addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public title addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public title addElement(Element element)
{
addElementToRegistry(element); | return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public title addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public title removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\title.java | 1 |
请完成以下Java代码 | public void closing(CommandContext commandContext) {
if (commandContext.getException() != null) {
return; // Not interested in events about exceptions
}
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
EventLogEntryEntityManager eventLogEntryEntityManager = processEngineConfiguration.getEventLogEntryEntityManager();
for (EventLoggerEventHandler eventHandler : eventHandlers) {
try {
eventLogEntryEntityManager.insert(eventHandler.generateEventLogEntry(commandContext), false);
} catch (Exception e) {
LOGGER.warn("Could not create event log", e);
}
}
}
@Override
public void afterSessionsFlush(CommandContext commandContext) {
} | @Override
public void closeFailure(CommandContext commandContext) {
}
@Override
public Integer order() {
return 100;
}
@Override
public boolean multipleAllowed() {
return false;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\event\logger\DatabaseEventFlusher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class Hikari {
private final DataSource dataSource;
private final ObjectProvider<MBeanExporter> mBeanExporter;
Hikari(DataSource dataSource, ObjectProvider<MBeanExporter> mBeanExporter) {
this.dataSource = dataSource;
this.mBeanExporter = mBeanExporter;
validateMBeans();
}
private void validateMBeans() {
HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(this.dataSource, HikariConfigMXBean.class,
HikariDataSource.class);
if (hikariDataSource != null && hikariDataSource.isRegisterMbeans()) {
this.mBeanExporter.ifUnique((exporter) -> exporter.addExcludedBean("dataSource"));
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty("spring.datasource.tomcat.jmx-enabled")
@ConditionalOnClass(DataSourceProxy.class)
@ConditionalOnSingleCandidate(DataSource.class)
static class TomcatDataSourceJmxConfiguration {
@Bean
@ConditionalOnMissingBean(name = "dataSourceMBean")
@Nullable Object dataSourceMBean(DataSource dataSource) {
DataSourceProxy dataSourceProxy = DataSourceUnwrapper.unwrap(dataSource, PoolConfiguration.class, | DataSourceProxy.class);
if (dataSourceProxy != null) {
try {
return dataSourceProxy.createPool().getJmxPool();
}
catch (SQLException ex) {
logger.warn("Cannot expose DataSource to JMX (could not connect)");
}
}
return null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceJmxConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Result<List<ProductEntity>> findProducts(ProdQueryReq prodQueryReq) {
return productService.findProducts(prodQueryReq);
}
@Override
public Result createCategoty(CategoryEntity categoryEntity) {
return productService.createCategoty(categoryEntity);
}
@Override
public Result modifyCategory(CategoryEntity categoryEntity) {
return productService.modifyCategory(categoryEntity);
}
@Override
public Result deleteCategory(String categoryId) {
return productService.deleteCategory(categoryId);
}
@Override
public Result<List<CategoryEntity>> findCategorys(CategoryQueryReq categoryQueryReq) {
return productService.findCategorys(categoryQueryReq);
} | @Override
public Result createBrand(BrandInsertReq brandInsertReq) {
return productService.createBrand(brandInsertReq);
}
@Override
public Result modifyBrand(BrandInsertReq brandInsertReq) {
return productService.modifyBrand(brandInsertReq);
}
@Override
public Result<List<BrandEntity>> findBrands(BrandQueryReq brandQueryReq) {
return productService.findBrands(brandQueryReq);
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\controller\product\ProductControllerImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getPassword() {
return this.properties.determinePassword();
}
@Override
public @Nullable String getVirtualHost() {
return this.properties.determineVirtualHost();
}
@Override
public List<Address> getAddresses() {
List<Address> addresses = new ArrayList<>();
for (String address : this.properties.determineAddresses()) {
int portSeparatorIndex = address.lastIndexOf(':');
String host = address.substring(0, portSeparatorIndex);
String port = address.substring(portSeparatorIndex + 1);
addresses.add(new Address(host, Integer.parseInt(port)));
}
return addresses; | }
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getSsl();
if (!ssl.determineEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
return this.sslBundles.getBundle(ssl.getBundle());
}
return null;
}
} | repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\PropertiesRabbitConnectionDetails.java | 2 |
请完成以下Java代码 | public class EdiInvoiceCandidateListener implements IInvoiceCandidateListener
{
public static final EdiInvoiceCandidateListener instance = new EdiInvoiceCandidateListener();
private final IEDIDocumentBL ediDocumentBL = Services.get(IEDIDocumentBL.class);
private EdiInvoiceCandidateListener()
{
}
@Override
public void onBeforeInvoiceComplete(final I_C_Invoice invoice, final List<I_C_Invoice_Candidate> fromCandidates)
{
final boolean isEdiEnabled = calculateEdiEnabled(fromCandidates);
final de.metas.edi.model.I_C_Invoice ediInvoice = InterfaceWrapperHelper.create(invoice, de.metas.edi.model.I_C_Invoice.class);
// make sure the EdiEnabled flag is set based on the invoice candidates of the invoice to be completed
ediDocumentBL.setEdiEnabled(ediInvoice, isEdiEnabled);
}
private boolean calculateEdiEnabled(@NonNull final List<I_C_Invoice_Candidate> fromCandidates)
{
if (fromCandidates.isEmpty())
{ | return false;
}
final boolean isEdiEnabled = InterfaceWrapperHelper.create(fromCandidates.get(0), de.metas.edi.model.I_C_Invoice_Candidate.class).isEdiEnabled();
for (int i = 0; i < fromCandidates.size(); i++)
{
final de.metas.edi.model.I_C_Invoice_Candidate candidate = InterfaceWrapperHelper.create(fromCandidates.get(i), de.metas.edi.model.I_C_Invoice_Candidate.class);
if (isEdiEnabled != candidate.isEdiEnabled())
{
throw new AdempiereException("IsEdiEnabled not consistent in candidates: " + fromCandidates);
}
}
return isEdiEnabled;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\spi\impl\EdiInvoiceCandidateListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | default @Nullable String getUsername() {
return null;
}
/**
* Login to authenticate against the broker.
* @return the login to authenticate against the broker or {@code null}
*/
default @Nullable String getPassword() {
return null;
}
/**
* Virtual host to use when connecting to the broker.
* @return the virtual host to use when connecting to the broker or {@code null}
*/
default @Nullable String getVirtualHost() {
return null;
}
/**
* List of addresses to which the client should connect. Must return at least one
* address.
* @return the list of addresses to which the client should connect
*/
List<Address> getAddresses();
/**
* Returns the first address.
* @return the first address
* @throws IllegalStateException if the address list is empty | */
default Address getFirstAddress() {
List<Address> addresses = getAddresses();
Assert.state(!addresses.isEmpty(), "Address list is empty");
return addresses.get(0);
}
/**
* SSL bundle to use.
* @return the SSL bundle to use
*/
default @Nullable SslBundle getSslBundle() {
return null;
}
/**
* A RabbitMQ address.
*
* @param host the host
* @param port the port
*/
record Address(String host, int port) {
}
} | repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitConnectionDetails.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TaskEntityStoreRepository {
private static final String DB_PATH = "db\\.myAppData";
private static final String ENTITY_TYPE = "Task";
public EntityId save(TaskEntity taskEntity) {
try (PersistentEntityStore entityStore = openStore()) {
AtomicReference<EntityId> idHolder = new AtomicReference<>();
entityStore.executeInTransaction(txn -> {
final Entity message = txn.newEntity(ENTITY_TYPE);
message.setProperty("description", taskEntity.getDescription());
message.setProperty("labels", taskEntity.getLabels());
idHolder.set(message.getId());
});
return idHolder.get();
}
}
private PersistentEntityStore openStore() {
return PersistentEntityStores.newInstance(DB_PATH);
}
public TaskEntity findOne(EntityId taskId) {
try (PersistentEntityStore entityStore = openStore()) {
AtomicReference<TaskEntity> taskEntity = new AtomicReference<>();
entityStore.executeInReadonlyTransaction(
txn -> taskEntity.set(mapToTaskEntity(txn.getEntity(taskId)))); | return taskEntity.get();
}
}
private TaskEntity mapToTaskEntity(Entity entity) {
return new TaskEntity(entity.getProperty("description").toString(),
entity.getProperty("labels").toString());
}
public List<TaskEntity> findAll() {
try (PersistentEntityStore entityStore = openStore()) {
List<TaskEntity> result = new ArrayList<>();
entityStore.executeInReadonlyTransaction(txn -> txn.getAll(ENTITY_TYPE)
.forEach(entity -> result.add(mapToTaskEntity(entity))));
return result;
}
}
public void deleteAll() {
try (PersistentEntityStore entityStore = openStore()) {
entityStore.clear();
}
}
} | repos\tutorials-master\persistence-modules\persistence-libraries\src\main\java\com\baeldung\jetbrainsxodus\TaskEntityStoreRepository.java | 2 |
请完成以下Java代码 | public class PitfallsWhenUsingFinally {
public String disregardsUnCaughtException() {
try {
System.out.println("Inside try");
throw new RuntimeException();
} finally {
System.out.println("Inside finally");
return "from finally";
}
}
public String ignoringOtherReturns() {
try {
System.out.println("Inside try"); | return "from try";
} finally {
System.out.println("Inside finally");
return "from finally";
}
}
public String throwsException() {
try {
System.out.println("Inside try");
return "from try";
} finally {
throw new RuntimeException();
}
}
} | repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\finallykeyword\PitfallsWhenUsingFinally.java | 1 |
请完成以下Java代码 | private static QtyRejectedWithReason extractQtyRejected(final I_PP_Order_IssueSchedule record)
{
final QtyRejectedReasonCode reasonCode = QtyRejectedReasonCode.ofNullableCode(record.getRejectReason()).orElse(null);
final BigDecimal qtyReject = record.getQtyReject();
if (qtyReject.signum() != 0 && reasonCode != null)
{
final UomId uomId = UomId.ofRepoId(record.getC_UOM_ID());
return QtyRejectedWithReason.of(Quantitys.of(qtyReject, uomId), reasonCode);
}
else
{
return null;
}
}
public ImmutableList<PPOrderIssueSchedule> getByOrderId(@NonNull final PPOrderId ppOrderId)
{
return queryBL.createQueryBuilder(I_PP_Order_IssueSchedule.class)
.addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_PP_Order_ID, ppOrderId)
.orderBy(I_PP_Order_IssueSchedule.COLUMNNAME_SeqNo)
.create()
.stream()
.map(PPOrderIssueScheduleRepository::toPPOrderIssueSchedule)
.collect(ImmutableList.toImmutableList());
}
public void saveChanges(final PPOrderIssueSchedule issueSchedule)
{
final I_PP_Order_IssueSchedule record = InterfaceWrapperHelper.load(issueSchedule.getId(), I_PP_Order_IssueSchedule.class);
final PPOrderIssueSchedule.Issued issued = issueSchedule.getIssued();
final boolean processed = issued != null;
final Quantity qtyIssued = issued != null ? issued.getQtyIssued() : null;
final QtyRejectedWithReason qtyRejected = issued != null ? issued.getQtyRejected() : null;
record.setSeqNo(issueSchedule.getSeqNo().toInt());
record.setProcessed(processed);
record.setQtyIssued(qtyIssued != null ? qtyIssued.toBigDecimal() : BigDecimal.ZERO);
record.setQtyReject(qtyRejected != null ? qtyRejected.toBigDecimal() : BigDecimal.ZERO);
record.setRejectReason(qtyRejected != null ? qtyRejected.getReasonCode().getCode() : null); | record.setQtyToIssue(issueSchedule.getQtyToIssue().toBigDecimal());
record.setC_UOM_ID(issueSchedule.getQtyToIssue().getUomId().getRepoId());
InterfaceWrapperHelper.save(record);
}
public void deleteNotProcessedByOrderId(@NonNull final PPOrderId ppOrderId)
{
queryBL.createQueryBuilder(I_PP_Order_IssueSchedule.class)
.addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_PP_Order_ID, ppOrderId)
.addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_Processed, false)
.create()
.delete();
}
public void deleteNotProcessedById(@NonNull final PPOrderIssueScheduleId issueScheduleId)
{
queryBL.createQueryBuilder(I_PP_Order_IssueSchedule.class)
.addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_PP_Order_IssueSchedule_ID, issueScheduleId)
.addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_Processed, false)
.create()
.delete();
}
public boolean matchesByOrderId(@NonNull final PPOrderId ppOrderId)
{
return queryBL.createQueryBuilder(I_PP_Order_IssueSchedule.class)
.addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_PP_Order_ID, ppOrderId)
.create()
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\issue_schedule\PPOrderIssueScheduleRepository.java | 1 |
请完成以下Java代码 | public static CallCredentials includeWhenPrivate(final CallCredentials callCredentials) {
return new IncludeWhenPrivateCallCredentials(callCredentials);
}
/**
* A call credentials implementation with increased security requirements. It ensures that the credentials and
* requests aren't send via an insecure connection. This wrapper does not have any other influence on the security
* of the underlying {@link CallCredentials} implementation.
*/
private static final class IncludeWhenPrivateCallCredentials extends CallCredentials {
private final CallCredentials callCredentials;
IncludeWhenPrivateCallCredentials(final CallCredentials callCredentials) {
this.callCredentials = callCredentials;
}
@Override
public void applyRequestMetadata(final RequestInfo requestInfo, final Executor appExecutor,
final MetadataApplier applier) {
if (isPrivacyGuaranteed(requestInfo.getSecurityLevel())) {
this.callCredentials.applyRequestMetadata(requestInfo, appExecutor, applier); | }
}
@Override
public void thisUsesUnstableApi() {} // API evolution in progress
@Override
public String toString() {
return "IncludeWhenPrivateCallCredentials [callCredentials=" + this.callCredentials + "]";
}
}
private CallCredentialsHelper() {}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\security\CallCredentialsHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | String getKind() throws Exception {
return findMethod("getKind").invoke(getInstance()).toString();
}
Object getLiteralValue() throws Exception {
if (this.literalTreeType.isAssignableFrom(getInstance().getClass())) {
return this.literalValueMethod.invoke(getInstance());
}
return null;
}
Object getFactoryValue() throws Exception {
if (this.methodInvocationTreeType.isAssignableFrom(getInstance().getClass())) {
List<?> arguments = (List<?>) this.methodInvocationArgumentsMethod.invoke(getInstance());
if (arguments.size() == 1) {
return new ExpressionTree(arguments.get(0)).getLiteralValue();
}
}
return null;
}
Member getSelectedMember() throws Exception {
if (this.memberSelectTreeType.isAssignableFrom(getInstance().getClass())) {
String expression = this.memberSelectTreeExpressionMethod.invoke(getInstance()).toString();
String identifier = this.memberSelectTreeIdentifierMethod.invoke(getInstance()).toString();
if (expression != null && identifier != null) {
return new Member(expression, identifier);
}
}
return null;
}
List<? extends ExpressionTree> getArrayExpression() throws Exception {
if (this.newArrayTreeType.isAssignableFrom(getInstance().getClass())) { | List<?> elements = (List<?>) this.arrayValueMethod.invoke(getInstance());
List<ExpressionTree> result = new ArrayList<>();
if (elements == null) {
return result;
}
for (Object element : elements) {
result.add(new ExpressionTree(element));
}
return result;
}
return null;
}
record Member(String expression, String identifier) {
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\fieldvalues\javac\ExpressionTree.java | 2 |
请在Spring Boot框架中完成以下Java代码 | DefaultCookieSerializer cookieSerializer(
ObjectProvider<DefaultCookieSerializerCustomizer> cookieSerializerCustomizers) {
DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
PropertyMapper map = PropertyMapper.get();
Assert.notNull(this.servletContext,
"ServletContext is required for session configuration in a war deployment");
SessionCookieConfig cookie = this.servletContext.getSessionCookieConfig();
map.from(cookie::getName).to(cookieSerializer::setCookieName);
map.from(cookie::getDomain).to(cookieSerializer::setDomainName);
map.from(cookie::getPath).to(cookieSerializer::setCookiePath);
map.from(cookie::isHttpOnly).to(cookieSerializer::setUseHttpOnlyCookie);
map.from(cookie::isSecure).to(cookieSerializer::setUseSecureCookie);
map.from(cookie::getMaxAge).to(cookieSerializer::setCookieMaxAge);
map.from(cookie.getAttribute("SameSite")).always().to(cookieSerializer::setSameSite);
map.from(cookie.getAttribute("Partitioned")).as(Boolean::valueOf).to(cookieSerializer::setPartitioned);
cookieSerializerCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(cookieSerializer));
return cookieSerializer;
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.REACTIVE)
static class ReactiveSessionConfiguration {
@Bean
SessionTimeout embeddedWebServerSessionTimeout(SessionProperties sessionProperties,
ServerProperties serverProperties) {
return () -> determineTimeout(sessionProperties, serverProperties.getReactive().getSession()::getTimeout);
}
}
/**
* Condition to trigger the creation of a {@link DefaultCookieSerializer}. This kicks
* in if either no {@link HttpSessionIdResolver} and {@link CookieSerializer} beans
* are registered, or if {@link CookieHttpSessionIdResolver} is registered but | * {@link CookieSerializer} is not.
*/
static class DefaultCookieSerializerCondition extends AnyNestedCondition {
DefaultCookieSerializerCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnMissingBean({ HttpSessionIdResolver.class, CookieSerializer.class })
static class NoComponentsAvailable {
}
@ConditionalOnBean(CookieHttpSessionIdResolver.class)
@ConditionalOnMissingBean(CookieSerializer.class)
static class CookieHttpSessionIdResolverAvailable {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\autoconfigure\SessionAutoConfiguration.java | 2 |
请完成以下Java代码 | private static OAuth2Error invalidTokenResponse(String message) {
return new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE, message, null);
}
private static Mono<AccessTokenResponse> oauth2AccessTokenResponse(TokenResponse tokenResponse) {
if (tokenResponse.indicatesSuccess()) {
return Mono.just(tokenResponse).cast(AccessTokenResponse.class);
}
TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
ErrorObject errorObject = tokenErrorResponse.getErrorObject();
OAuth2Error oauth2Error = getOAuth2Error(errorObject);
return Mono.error(new OAuth2AuthorizationException(oauth2Error));
}
private static OAuth2Error getOAuth2Error(ErrorObject errorObject) {
if (errorObject == null) {
return new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR);
}
String code = (errorObject.getCode() != null) ? errorObject.getCode() : OAuth2ErrorCodes.SERVER_ERROR;
String description = errorObject.getDescription();
String uri = (errorObject.getURI() != null) ? errorObject.getURI().toString() : null;
return new OAuth2Error(code, description, uri);
}
private static OAuth2AccessTokenResponse oauth2AccessTokenResponse(AccessTokenResponse accessTokenResponse) {
AccessToken accessToken = accessTokenResponse.getTokens().getAccessToken(); | OAuth2AccessToken.TokenType accessTokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessToken.getType().getValue())) {
accessTokenType = OAuth2AccessToken.TokenType.BEARER;
}
long expiresIn = accessToken.getLifetime();
Set<String> scopes = (accessToken.getScope() != null)
? new LinkedHashSet<>(accessToken.getScope().toStringList()) : Collections.emptySet();
String refreshToken = null;
if (accessTokenResponse.getTokens().getRefreshToken() != null) {
refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
}
Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
// @formatter:off
return OAuth2AccessTokenResponse.withToken(accessToken.getValue())
.tokenType(accessTokenType)
.expiresIn(expiresIn)
.scopes(scopes)
.refreshToken(refreshToken)
.additionalParameters(additionalParameters)
.build();
// @formatter:on
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\web\reactive\function\OAuth2AccessTokenResponseBodyExtractor.java | 1 |
请完成以下Java代码 | private final void loadResultsAndShow(final ProcessExecutionResult result)
{
final StringBuilder messageText = new StringBuilder();
// Show process logs if any
if (result.isShowProcessLogs())
{
//
// Update message
messageText.append("<p><font color=\"").append(result.isError() ? "#FF0000" : "#0000FF").append("\">** ")
.append(result.getSummary())
.append("</font></p>");
messageText.append(result.getLogInfo(true));
}
resultMessagePane.setText(messageText.toString());
resultMessagePane.moveCaretToEnd(); // scroll down
result.setErrorWasReportedToUser();
//
// Show the results panel
showCard(CARDNAME_ProcessResult);
//
// Update UI
windowShow();
}
/**
* Message panel component
*
* @author tsa
*
*/
private static final class MessagePanel extends JScrollPane
{
private static final long serialVersionUID = 1L;
private final StringBuffer messageBuf = new StringBuffer();
private final JEditorPane message = new JEditorPane()
{
private static final long serialVersionUID = 1L;
@Override
public Dimension getPreferredSize()
{
final Dimension d = super.getPreferredSize();
final Dimension m = getMaximumSize();
if (d.height > m.height || d.width > m.width)
{
final Dimension d1 = new Dimension();
d1.height = Math.min(d.height, m.height);
d1.width = Math.min(d.width, m.width);
return d1;
}
else
{
return d;
}
}
};
public MessagePanel()
{
super();
setBorder(null);
setViewportView(message);
message.setContentType("text/html");
message.setEditable(false);
message.setBackground(Color.white);
message.setFocusable(true); | }
public void moveCaretToEnd()
{
message.setCaretPosition(message.getDocument().getLength()); // scroll down
}
public void setText(final String text)
{
messageBuf.setLength(0);
appendText(text);
}
public void appendText(final String text)
{
messageBuf.append(text);
message.setText(messageBuf.toString());
}
@Override
public Dimension getPreferredSize()
{
final Dimension d = super.getPreferredSize();
final Dimension m = getMaximumSize();
if (d.height > m.height || d.width > m.width)
{
final Dimension d1 = new Dimension();
d1.height = Math.min(d.height, m.height);
d1.width = Math.min(d.width, m.width);
return d1;
}
else
{
return d;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessPanel.java | 1 |
请完成以下Java代码 | public class MembershipEntityManagerImpl
extends AbstractIdmEngineEntityManager<MembershipEntity, MembershipDataManager> implements MembershipEntityManager {
public MembershipEntityManagerImpl(IdmEngineConfiguration idmEngineConfiguration, MembershipDataManager membershipDataManager) {
super(idmEngineConfiguration, membershipDataManager);
}
@Override
public void createMembership(String userId, String groupId) {
MembershipEntity membershipEntity = create();
membershipEntity.setUserId(userId);
membershipEntity.setGroupId(groupId);
insert(membershipEntity, false);
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableIdmEventBuilder.createMembershipEvent(
FlowableIdmEventType.MEMBERSHIP_CREATED, groupId, userId), engineConfiguration.getEngineCfgKey());
}
}
@Override
public void deleteMembership(String userId, String groupId) {
dataManager.deleteMembership(userId, groupId);
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableIdmEventBuilder.createMembershipEvent( | FlowableIdmEventType.MEMBERSHIP_DELETED, groupId, userId), engineConfiguration.getEngineCfgKey());
}
}
@Override
public void deleteMembershipByGroupId(String groupId) {
dataManager.deleteMembershipByGroupId(groupId);
}
@Override
public void deleteMembershipByUserId(String userId) {
dataManager.deleteMembershipByUserId(userId);
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\MembershipEntityManagerImpl.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_R_IssueStatus[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName | @return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Issue Status.
@param R_IssueStatus_ID
Status of an Issue
*/
public void setR_IssueStatus_ID (int R_IssueStatus_ID)
{
if (R_IssueStatus_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_IssueStatus_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_IssueStatus_ID, Integer.valueOf(R_IssueStatus_ID));
}
/** Get Issue Status.
@return Status of an Issue
*/
public int getR_IssueStatus_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueStatus_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueStatus.java | 1 |
请完成以下Java代码 | public PartyIdentificationSEPA3 getCdtrSchmeId() {
return cdtrSchmeId;
}
/**
* Sets the value of the cdtrSchmeId property.
*
* @param value
* allowed object is
* {@link PartyIdentificationSEPA3 }
*
*/
public void setCdtrSchmeId(PartyIdentificationSEPA3 value) {
this.cdtrSchmeId = value;
}
/**
* Gets the value of the drctDbtTxInf property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the drctDbtTxInf property.
* | * <p>
* For example, to add a new item, do as follows:
* <pre>
* getDrctDbtTxInf().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DirectDebitTransactionInformationSDD }
*
*
*/
public List<DirectDebitTransactionInformationSDD> getDrctDbtTxInf() {
if (drctDbtTxInf == null) {
drctDbtTxInf = new ArrayList<DirectDebitTransactionInformationSDD>();
}
return this.drctDbtTxInf;
}
} | 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\PaymentInstructionInformationSDD.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ArticleFavoriteApi {
private ArticleFavoriteRepository articleFavoriteRepository;
private ArticleRepository articleRepository;
private ArticleQueryService articleQueryService;
@PostMapping
public ResponseEntity favoriteArticle(
@PathVariable("slug") String slug, @AuthenticationPrincipal User user) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
ArticleFavorite articleFavorite = new ArticleFavorite(article.getId(), user.getId());
articleFavoriteRepository.save(articleFavorite);
return responseArticleData(articleQueryService.findBySlug(slug, user).get());
}
@DeleteMapping
public ResponseEntity unfavoriteArticle(
@PathVariable("slug") String slug, @AuthenticationPrincipal User user) {
Article article = | articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
articleFavoriteRepository
.find(article.getId(), user.getId())
.ifPresent(
favorite -> {
articleFavoriteRepository.remove(favorite);
});
return responseArticleData(articleQueryService.findBySlug(slug, user).get());
}
private ResponseEntity<HashMap<String, Object>> responseArticleData(
final ArticleData articleData) {
return ResponseEntity.ok(
new HashMap<String, Object>() {
{
put("article", articleData);
}
});
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\ArticleFavoriteApi.java | 2 |
请完成以下Java代码 | private boolean isImmutableConfigurationPropertiesBeanDefinition(BeanDefinition beanDefinition) {
return BindMethod.VALUE_OBJECT.equals(BindMethodAttribute.get(beanDefinition));
}
private static class ConfigurationPropertiesBeanRegistrationCodeFragments
extends BeanRegistrationCodeFragmentsDecorator {
private static final String REGISTERED_BEAN_PARAMETER_NAME = "registeredBean";
private final RegisteredBean registeredBean;
ConfigurationPropertiesBeanRegistrationCodeFragments(BeanRegistrationCodeFragments codeFragments,
RegisteredBean registeredBean) {
super(codeFragments);
this.registeredBean = registeredBean;
}
@Override
public CodeBlock generateSetBeanDefinitionPropertiesCode(GenerationContext generationContext,
BeanRegistrationCode beanRegistrationCode, RootBeanDefinition beanDefinition,
Predicate<String> attributeFilter) {
return super.generateSetBeanDefinitionPropertiesCode(generationContext, beanRegistrationCode,
beanDefinition, attributeFilter.or(BindMethodAttribute.NAME::equals));
}
@Override
public ClassName getTarget(RegisteredBean registeredBean) {
return ClassName.get(this.registeredBean.getBeanClass());
}
@Override
public CodeBlock generateInstanceSupplierCode(GenerationContext generationContext,
BeanRegistrationCode beanRegistrationCode, boolean allowDirectSupplierShortcut) {
GeneratedMethod generatedMethod = beanRegistrationCode.getMethods().add("getInstance", (method) -> {
Class<?> beanClass = this.registeredBean.getBeanClass();
method.addJavadoc("Get the bean instance for '$L'.", this.registeredBean.getBeanName()) | .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
.returns(beanClass)
.addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER_NAME)
.addStatement("$T beanFactory = registeredBean.getBeanFactory()", BeanFactory.class)
.addStatement("$T beanName = registeredBean.getBeanName()", String.class)
.addStatement("$T<?> beanClass = registeredBean.getBeanClass()", Class.class)
.addStatement("return ($T) $T.from(beanFactory, beanName, beanClass)", beanClass,
ConstructorBound.class);
});
return CodeBlock.of("$T.of($T::$L)", InstanceSupplier.class, beanRegistrationCode.getClassName(),
generatedMethod.getName());
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesBeanRegistrationAotProcessor.java | 1 |
请完成以下Java代码 | public void setAD_Field_ID (int AD_Field_ID)
{
if (AD_Field_ID < 1)
set_Value (COLUMNNAME_AD_Field_ID, null);
else
set_Value (COLUMNNAME_AD_Field_ID, Integer.valueOf(AD_Field_ID));
}
/** Get Feld.
@return Ein Feld einer Datenbanktabelle
*/
@Override
public int getAD_Field_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Field_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Tab getAD_Tab() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Tab_ID, org.compiere.model.I_AD_Tab.class);
}
@Override
public void setAD_Tab(org.compiere.model.I_AD_Tab AD_Tab)
{
set_ValueFromPO(COLUMNNAME_AD_Tab_ID, org.compiere.model.I_AD_Tab.class, AD_Tab);
}
/** Set Register.
@param AD_Tab_ID
Register auf einem Fenster
*/
@Override
public void setAD_Tab_ID (int AD_Tab_ID)
{
if (AD_Tab_ID < 1)
set_Value (COLUMNNAME_AD_Tab_ID, null);
else
set_Value (COLUMNNAME_AD_Tab_ID, Integer.valueOf(AD_Tab_ID));
}
/** Get Register.
@return Register auf einem Fenster
*/
@Override
public int getAD_Tab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
@Override
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
/** Set Fenster.
@param AD_Window_ID
Eingabe- oder Anzeige-Fenster
*/
@Override
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_Value (COLUMNNAME_AD_Window_ID, null);
else
set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Fenster.
@return Eingabe- oder Anzeige-Fenster
*/
@Override
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Element_Link.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Department> getDepartments() {
return departments;
}
public void setDepartments(List<Department> departments) {
this.departments = departments;
} | public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
@Override
public String toString() {
return "Organization [id=" + id + ", name=" + name + ", address=" + address + "]";
}
} | repos\sample-spring-microservices-new-master\organization-service\src\main\java\pl\piomin\services\organization\model\Organization.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static void validateFields(Object data, String errorPrefix) {
Set<ConstraintViolation<Object>> constraintsViolations = fieldsValidator.validate(data);
if (!constraintsViolations.isEmpty()) {
throw new DataValidationException(errorPrefix + getErrorMessage(constraintsViolations));
}
}
public static String getErrorMessage(Collection<ConstraintViolation<Object>> constraintsViolations) {
return constraintsViolations.stream()
.map(ConstraintValidator::getErrorMessage)
.distinct().sorted().collect(Collectors.joining(", "));
}
public static String getErrorMessage(ConstraintViolation<Object> constraintViolation) {
ConstraintDescriptor<?> constraintDescriptor = constraintViolation.getConstraintDescriptor();
String property = (String) constraintDescriptor.getAttributes().get("fieldName");
if (StringUtils.isEmpty(property) && !(constraintDescriptor.getAnnotation() instanceof AssertTrue)) {
property = Iterators.getLast(constraintViolation.getPropertyPath().iterator()).toString();
}
String error = "";
if (StringUtils.isNotEmpty(property)) {
error += property + " ";
}
error += constraintViolation.getMessage();
return error;
}
private static void initializeValidators() {
HibernateValidatorConfiguration validatorConfiguration = Validation.byProvider(HibernateValidator.class).configure();
ConstraintMapping constraintMapping = getCustomConstraintMapping();
validatorConfiguration.addMapping(constraintMapping); | try (var validatorFactory = validatorConfiguration.buildValidatorFactory()) {
fieldsValidator = validatorFactory.getValidator();
}
}
@Bean
public LocalValidatorFactoryBean validatorFactoryBean() {
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.setConfigurationInitializer(configuration -> {
((ConfigurationImpl) configuration).addMapping(getCustomConstraintMapping());
});
return localValidatorFactoryBean;
}
private static ConstraintMapping getCustomConstraintMapping() {
ConstraintMapping constraintMapping = new DefaultConstraintMapping(null);
constraintMapping.constraintDefinition(NoXss.class).validatedBy(NoXssValidator.class);
constraintMapping.constraintDefinition(Length.class).validatedBy(StringLengthValidator.class);
constraintMapping.constraintDefinition(RateLimit.class).validatedBy(RateLimitValidator.class);
constraintMapping.constraintDefinition(NoNullChar.class).validatedBy(NoNullCharValidator.class);
constraintMapping.constraintDefinition(ValidJsonSchema.class).validatedBy(JsonSchemaValidator.class);
return constraintMapping;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\ConstraintValidator.java | 2 |
请完成以下Java代码 | public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** 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.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI.java | 1 |
请完成以下Java代码 | public List<MaterialCockpitRow> getIncludedRows()
{
return includedRows;
}
@Override
public DocumentId getId()
{
return documentId;
}
@Override
public IViewRowType getType()
{
return rowType;
}
@Override
public DocumentPath getDocumentPath()
{
return documentPath;
}
/**
* Return false, because with true, all rows are "grayed" out. This does not mean that the rows are editable.
*/
@Override
public boolean isProcessed()
{
return false;
} | @Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
public DocumentZoomIntoInfo getZoomIntoInfo(@NonNull final String fieldName)
{
if (FIELDNAME_M_Product_ID.equals(fieldName))
{
return lookups.getZoomInto(productId);
}
else
{
throw new AdempiereException("Field " + fieldName + " does not support zoom info");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRow.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_JobCategory[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Position Category.
@param C_JobCategory_ID
Job Position Category
*/
public void setC_JobCategory_ID (int C_JobCategory_ID)
{
if (C_JobCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_JobCategory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_JobCategory_ID, Integer.valueOf(C_JobCategory_ID));
}
/** Get Position Category.
@return Job Position Category
*/
public int getC_JobCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_JobCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription () | {
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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 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_C_JobCategory.java | 1 |
请完成以下Java代码 | public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public String getTargetNamespace() {
return targetNamespaceAttribute.getValue(this);
}
public void setTargetNamespace(String namespace) {
targetNamespaceAttribute.setValue(this, namespace);
}
public String getExpressionLanguage() {
return expressionLanguageAttribute.getValue(this);
}
public void setExpressionLanguage(String expressionLanguage) {
expressionLanguageAttribute.setValue(this, expressionLanguage);
}
public String getTypeLanguage() {
return typeLanguageAttribute.getValue(this);
}
public void setTypeLanguage(String typeLanguage) {
typeLanguageAttribute.setValue(this, typeLanguage);
}
public String getExporter() {
return exporterAttribute.getValue(this);
} | public void setExporter(String exporter) {
exporterAttribute.setValue(this, exporter);
}
public String getExporterVersion() {
return exporterVersionAttribute.getValue(this);
}
public void setExporterVersion(String exporterVersion) {
exporterVersionAttribute.setValue(this, exporterVersion);
}
public Collection<Import> getImports() {
return importCollection.get(this);
}
public Collection<Extension> getExtensions() {
return extensionCollection.get(this);
}
public Collection<RootElement> getRootElements() {
return rootElementCollection.get(this);
}
public Collection<BpmnDiagram> getBpmDiagrams() {
return bpmnDiagramCollection.get(this);
}
public Collection<Relationship> getRelationships() {
return relationshipCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DefinitionsImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public NursingHome email(String email) {
this.email = email;
return this;
}
/**
* Get email
* @return email
**/
@Schema(example = "wagemann@berliner-stadtmission.de", description = "")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public NursingHome timestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return timestamp
**/
@Schema(description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) { | return false;
}
NursingHome nursingHome = (NursingHome) o;
return Objects.equals(this._id, nursingHome._id) &&
Objects.equals(this.name, nursingHome.name) &&
Objects.equals(this.address, nursingHome.address) &&
Objects.equals(this.postalCode, nursingHome.postalCode) &&
Objects.equals(this.city, nursingHome.city) &&
Objects.equals(this.phone, nursingHome.phone) &&
Objects.equals(this.fax, nursingHome.fax) &&
Objects.equals(this.email, nursingHome.email) &&
Objects.equals(this.timestamp, nursingHome.timestamp);
}
@Override
public int hashCode() {
return Objects.hash(_id, name, address, postalCode, city, phone, fax, email, timestamp);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class NursingHome {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" fax: ").append(toIndentedString(fax)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\NursingHome.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setFromTime2(Integer value) {
this.fromTime2 = value;
}
/**
* Gets the value of the toTime2 property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getToTime2() {
return toTime2;
}
/**
* Sets the value of the toTime2 property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setToTime2(Integer value) {
this.toTime2 = value;
}
/**
* Gets the value of the extraPickup property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isExtraPickup() {
return extraPickup; | }
/**
* Sets the value of the extraPickup property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setExtraPickup(Boolean value) {
this.extraPickup = value;
}
/**
* Gets the value of the collectionRequestAddress property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getCollectionRequestAddress() {
return collectionRequestAddress;
}
/**
* Sets the value of the collectionRequestAddress property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setCollectionRequestAddress(Address value) {
this.collectionRequestAddress = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Pickup.java | 2 |
请完成以下Java代码 | protected void onRecordAndChildrenCopied(final PO to, final PO from, final CopyTemplate template) {}
private Iterator<Object> retrieveChildPOsForParent(final CopyTemplate childTemplate, final PO parentPO)
{
final IQueryBuilder<Object> queryBuilder = queryBL.createQueryBuilder(childTemplate.getTableName())
.addEqualsFilter(childTemplate.getLinkColumnName(), parentPO.get_ID());
childTemplate.getOrderByColumnNames().forEach(queryBuilder::orderBy);
return queryBuilder
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, false)
.create()
.iterate(Object.class);
}
/**
* @return true if the record shall be copied
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected boolean isCopyRecord(final PO fromPO) {return true;}
protected boolean isCopyChildRecord(final CopyTemplate parentTemplate, final PO fromChildPO, final CopyTemplate childTemplate) {return true;}
@Override
public final GeneralCopyRecordSupport setParentLink(@NonNull final PO parentPO, @NonNull final String parentLinkColumnName)
{
this.parentPO = parentPO;
this.parentLinkColumnName = parentLinkColumnName;
return this;
}
@Override
public final GeneralCopyRecordSupport setAdWindowId(final @Nullable AdWindowId adWindowId)
{
this.adWindowId = adWindowId;
return this;
}
@SuppressWarnings("SameParameterValue")
@Nullable | protected final <T> T getParentModel(final Class<T> modelType)
{
return parentPO != null ? InterfaceWrapperHelper.create(parentPO, modelType) : null;
}
private int getParentID()
{
return parentPO != null ? parentPO.get_ID() : -1;
}
/**
* Allows other modules to install customer code to be executed each time a record was copied.
*/
@Override
public final GeneralCopyRecordSupport onRecordCopied(@NonNull final OnRecordCopiedListener listener)
{
if (!recordCopiedListeners.contains(listener))
{
recordCopiedListeners.add(listener);
}
return this;
}
@Override
public final CopyRecordSupport onChildRecordCopied(@NonNull final OnRecordCopiedListener listener)
{
if (!childRecordCopiedListeners.contains(listener))
{
childRecordCopiedListeners.add(listener);
}
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\GeneralCopyRecordSupport.java | 1 |
请完成以下Spring Boot application配置 | management:
endpoints:
# Actuator HTTP 配置项,对应 WebEndpointProperties 配置类
web:
base-path: /actuator # Actuator 提供的 API 接口的根目录。默认为 /actuator
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
exclude: # 在 include 的基础上,需要排除的端点。通过设置 * ,可以排除所有端点。
# server:
# port: 8081
# endpoint:
# shutdown:
# enabled: true
spring:
# Spring Securit | y 配置项,对应 SecurityProperties 配置类
security:
# 配置默认的 InMemoryUserDetailsManager 的用户账号与密码。
user:
name: user # 账号
password: user # 密码
roles: ADMIN # 拥有角色 | repos\SpringBoot-Labs-master\lab-34\lab-34-actuator-demo-security\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public class MemoryDataSet extends AbstractDataSet
{
List<Document> documentList;
boolean editMode;
public MemoryDataSet()
{
super();
documentList = new LinkedList<Document>();
}
public MemoryDataSet(AbstractModel model)
{
super(model);
documentList = new LinkedList<Document>();
}
@Override
public Document add(String category, String text)
{
if (editMode) return null;
Document document = convert(category, text);
documentList.add(document);
return document;
}
@Override
public int size()
{
return documentList.size();
}
@Override
public void clear() | {
documentList.clear();
}
@Override
public IDataSet shrink(int[] idMap)
{
Iterator<Document> iterator = iterator();
while (iterator.hasNext())
{
Document document = iterator.next();
FrequencyMap<Integer> tfMap = new FrequencyMap<Integer>();
for (Map.Entry<Integer, int[]> entry : document.tfMap.entrySet())
{
Integer feature = entry.getKey();
if (idMap[feature] == -1) continue;
tfMap.put(idMap[feature], entry.getValue());
}
// 检查是否是空白文档
if (tfMap.size() == 0) iterator.remove();
else document.tfMap = tfMap;
}
return this;
}
@Override
public Iterator<Document> iterator()
{
return documentList.iterator();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\MemoryDataSet.java | 1 |
请完成以下Java代码 | 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 Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) { | this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", sort=").append(sort);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderReturnReason.java | 1 |
请完成以下Java代码 | public void initExecutor() {
edgeEventExecutor = Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName("edge-event-service"));
}
@PreDestroy
public void shutdownExecutor() {
if (edgeEventExecutor != null) {
edgeEventExecutor.shutdown();
}
}
@Override
public ListenableFuture<Void> saveAsync(EdgeEvent edgeEvent) {
validateEdgeEvent(edgeEvent);
ListenableFuture<Void> saveFuture = edgeEventDao.saveAsync(edgeEvent);
Futures.addCallback(saveFuture, new FutureCallback<>() {
@Override | public void onSuccess(Void result) {
statsCounterService.ifPresent(statsCounterService ->
statsCounterService.recordEvent(EdgeStatsKey.DOWNLINK_MSGS_ADDED, edgeEvent.getTenantId(), edgeEvent.getEdgeId(), 1));
eventPublisher.publishEvent(SaveEntityEvent.builder()
.tenantId(edgeEvent.getTenantId())
.entityId(edgeEvent.getEdgeId())
.entity(edgeEvent)
.build());
}
@Override
public void onFailure(@NotNull Throwable throwable) {}
}, edgeEventExecutor);
return saveFuture;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\edge\PostgresEdgeEventService.java | 1 |
请完成以下Java代码 | public void connectionAcquired(Call call, Connection connection) {
logTimedEvent("connectionAcquired");
}
@Override
public void connectionReleased(Call call, Connection connection) {
logTimedEvent("connectionReleased");
}
@Override
public void requestHeadersStart(Call call) {
logTimedEvent("requestHeadersStart");
}
@Override
public void requestHeadersEnd(Call call, Request request) {
logTimedEvent("requestHeadersEnd");
}
@Override
public void requestBodyStart(Call call) {
logTimedEvent("requestBodyStart");
}
@Override
public void requestBodyEnd(Call call, long byteCount) {
logTimedEvent("requestBodyEnd");
}
@Override
public void requestFailed(Call call, IOException ioe) {
logTimedEvent("requestFailed");
}
@Override
public void responseHeadersStart(Call call) {
logTimedEvent("responseHeadersStart");
}
@Override
public void responseHeadersEnd(Call call, Response response) {
logTimedEvent("responseHeadersEnd");
}
@Override
public void responseBodyStart(Call call) {
logTimedEvent("responseBodyStart");
}
@Override
public void responseBodyEnd(Call call, long byteCount) {
logTimedEvent("responseBodyEnd"); | }
@Override
public void responseFailed(Call call, IOException ioe) {
logTimedEvent("responseFailed");
}
@Override
public void callEnd(Call call) {
logTimedEvent("callEnd");
}
@Override
public void callFailed(Call call, IOException ioe) {
logTimedEvent("callFailed");
}
@Override
public void canceled(Call call) {
logTimedEvent("canceled");
}
} | repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\okhttp\events\EventTimer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FMPXMLRESULT
{
@JacksonXmlProperty(localName = "ERRORCODE")
String errorCode;
@JacksonXmlProperty(localName = "PRODUCT")
PRODUCT product;
@JacksonXmlProperty(localName = "DATABASE")
DATABASE database;
@JacksonXmlProperty(localName = "METADATA")
METADATA metadata;
@JacksonXmlProperty(localName = "RESULTSET")
RESULTSET resultset;
@Builder(toBuilder = true)
@JsonCreator
public FMPXMLRESULT(
@JacksonXmlProperty(localName = "ERRORCODE") final String errorCode,
@JacksonXmlProperty(localName = "PRODUCT") final PRODUCT product,
@JacksonXmlProperty(localName = "DATABASE") final DATABASE database,
@JacksonXmlProperty(localName = "METADATA") final METADATA metadata,
@JacksonXmlProperty(localName = "RESULTSET") final RESULTSET resultset)
{
this.errorCode = errorCode;
this.product = product;
this.database = database; | this.metadata = metadata;
this.resultset = resultset;
}
@JsonIgnore
public boolean isEmpty()
{
return metadata == null
|| metadata.getFields() == null
|| metadata.getFields().isEmpty()
|| resultset == null
|| resultset.getRows() == null
|| resultset.getRows().isEmpty();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-filemaker\src\main\java\de\metas\common\filemaker\FMPXMLRESULT.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TaxId implements RepoIdAware
{
@JsonCreator
@NonNull
public static TaxId ofRepoId(final int repoId)
{
return new TaxId(repoId);
}
@Nullable
public static TaxId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<TaxId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final TaxId id)
{
return id != null ? id.getRepoId() : -1;
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static int toRepoId(@Nullable final Optional<TaxId> optional)
{
//noinspection OptionalAssignedToNull
final TaxId id = optional != null ? optional.orElse(null) : null;
return toRepoId(id);
} | public static int toRepoIdOrNoTaxId(@Nullable final TaxId id)
{
return id != null ? id.getRepoId() : Tax.C_TAX_ID_NO_TAX_FOUND;
}
int repoId;
private TaxId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Tax_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public boolean isNoTaxId()
{
return repoId == Tax.C_TAX_ID_NO_TAX_FOUND;
}
public static boolean equals(@Nullable TaxId id1, @Nullable TaxId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\TaxId.java | 2 |
请完成以下Java代码 | protected boolean isJobReacquired(CommandContext commandContext) {
// if persisted job's lockExpirationTime is different, then it's been already re-acquired
JobEntity persistedJob = commandContext.getJobManager().findJobById(jobFailureCollector.getJobId());
JobEntity job = jobFailureCollector.getJob();
if (persistedJob == null || persistedJob.getLockExpirationTime() == null) {
return false;
}
return !persistedJob.getLockExpirationTime().equals(job.getLockExpirationTime());
}
private void initTotalRetries(CommandContext commandContext) {
totalRetries = commandContext.getProcessEngineConfiguration().getFailedJobListenerMaxRetries();
}
protected void fireHistoricJobFailedEvt(JobEntity job) {
CommandContext commandContext = Context.getCommandContext();
// the given job failed and a rollback happened,
// that's why we have to increment the job
// sequence counter once again
job.incrementSequenceCounter();
commandContext
.getHistoricJobLogManager()
.fireJobFailedEvent(job, jobFailureCollector.getFailure());
}
protected void logJobFailure(CommandContext commandContext) {
if (commandContext.getProcessEngineConfiguration().isMetricsEnabled()) {
commandContext.getProcessEngineConfiguration()
.getMetricsRegistry()
.markOccurrence(Metrics.JOB_FAILED);
}
}
public void incrementCountRetries() {
this.countRetries++;
} | public int getRetriesLeft() {
return Math.max(0, totalRetries - countRetries);
}
protected class FailedJobListenerCmd implements Command<Void> {
protected String jobId;
protected Command<Object> cmd;
public FailedJobListenerCmd(String jobId, Command<Object> cmd) {
this.jobId = jobId;
this.cmd = cmd;
}
@Override
public Void execute(CommandContext commandContext) {
JobEntity job = commandContext
.getJobManager()
.findJobById(jobId);
if (job != null) {
job.setFailedActivityId(jobFailureCollector.getFailedActivityId());
fireHistoricJobFailedEvt(job);
cmd.execute(commandContext);
} else {
LOG.debugFailedJobNotFound(jobId);
}
return null;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\FailedJobListener.java | 1 |
请完成以下Java代码 | public void setIsStaled (boolean IsStaled)
{
throw new IllegalArgumentException ("IsStaled is virtual column"); }
/** Get Zu aktualisieren.
@return Zu aktualisieren */
@Override
public boolean isStaled ()
{
Object oo = get_Value(COLUMNNAME_IsStaled);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Massenaustritt.
@param IsWriteOff Massenaustritt */
@Override
public void setIsWriteOff (boolean IsWriteOff)
{
set_Value (COLUMNNAME_IsWriteOff, Boolean.valueOf(IsWriteOff));
}
/** Get Massenaustritt.
@return Massenaustritt */
@Override
public boolean isWriteOff ()
{
Object oo = get_Value(COLUMNNAME_IsWriteOff);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Offener Betrag.
@param OpenAmt Offener Betrag */
@Override
public void setOpenAmt (java.math.BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Offener Betrag.
@return Offener Betrag */
@Override
public java.math.BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{ | set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set 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 Gesamtbetrag.
@param TotalAmt Gesamtbetrag */
@Override
public void setTotalAmt (java.math.BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Gesamtbetrag.
@return Gesamtbetrag */
@Override
public java.math.BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate.java | 1 |
请完成以下Java代码 | public Mono<? extends EvaluationContextExtension> getExtension() {
return Mono.deferContextual(contextView -> Mono.just(new TenantExtension(contextView.get(Tenant.class))));
}
@Override
public String getExtensionId() {
return "my-reactive-tenant-extension";
}
}
/**
* Actual extension providing access to the {@link Tenant} value object.
*/
@RequiredArgsConstructor
static class TenantExtension implements EvaluationContextExtension {
private final Tenant tenant;
@Override
public String getExtensionId() {
return "my-tenant-extension";
} | @Override
public Tenant getRootObject() {
return tenant;
}
}
/**
* The root object.
*/
@Value
public static class Tenant {
String tenantId;
}
} | repos\spring-data-examples-main\cassandra\reactive\src\main\java\example\springdata\cassandra\spel\ApplicationConfiguration.java | 1 |
请完成以下Java代码 | public ITranslatableString ofTimeZone(@NonNull final ZoneId timeZone, @NonNull final TextStyle textStyle)
{
return TimeZoneTranslatableString.ofZoneId(timeZone, textStyle);
}
public static ITranslatableString parse(@Nullable final String text)
{
if (text == null || text.isEmpty())
{
return TranslatableStrings.empty();
}
final TranslatableStringBuilder builder = TranslatableStrings.builder();
String inStr = text;
int idx = inStr.indexOf('@');
while (idx != -1)
{
builder.append(inStr.substring(0, idx)); // up to @
inStr = inStr.substring(idx + 1); // from first @
final int j = inStr.indexOf('@'); // next @
if (j < 0) // no second tag
{
inStr = "@" + inStr;
break;
}
final String token = inStr.substring(0, j);
if (token.isEmpty())
{
builder.append("@");
}
else
{
builder.appendADElement(token); // replace context
}
inStr = inStr.substring(j + 1); // from second @
idx = inStr.indexOf('@');
}
// add remainder
if (inStr.length() > 0)
{
builder.append(inStr);
}
return builder.build();
} | public static boolean isPossibleTranslatableString(final String text)
{
return text != null && text.indexOf('@') >= 0;
}
public static ITranslatableString adElementOrMessage(@NonNull final String columnName)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
return msgBL.translatable(columnName);
}
public static ITranslatableString adMessage(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
return msgBL.getTranslatableMsgText(adMessage, msgParameters);
}
public static ITranslatableString adRefList(final int adReferenceId, @NonNull final String value)
{
return adRefList(ReferenceId.ofRepoId(adReferenceId), value);
}
public static ITranslatableString adRefList(@NonNull final ReferenceId adReferenceId, @NonNull final ReferenceListAwareEnum value)
{
return adRefList(adReferenceId, value.getCode());
}
public static ITranslatableString adRefList(@NonNull final ReferenceId adReferenceId, @NonNull final String value)
{
final ADReferenceService adReferenceService = ADReferenceService.get();
return adReferenceService.getRefListById(adReferenceId)
.getItemByValue(value)
.map(ADRefListItem::getName)
.orElseGet(() -> anyLanguage(value));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TranslatableStrings.java | 1 |
请完成以下Java代码 | public OrderLineBuilder productId(final ProductId productId)
{
assertNotBuilt();
this.productId = productId;
return this;
}
public OrderLineBuilder piItemProductId(@Nullable final HUPIItemProductId piItemProductId)
{
assertNotBuilt();
this.piItemProductId = piItemProductId;
return this;
}
private ProductId getProductId()
{
return productId;
}
public OrderLineBuilder asiId(@NonNull final AttributeSetInstanceId asiId)
{
assertNotBuilt();
this.asiId = asiId;
return this;
}
public OrderLineBuilder qty(@NonNull final Quantity qty)
{
assertNotBuilt();
this.qty = qty;
return this;
}
public OrderLineBuilder addQty(@NonNull final Quantity qtyToAdd)
{
assertNotBuilt();
return qty(Quantity.addNullables(this.qty, qtyToAdd));
}
public OrderLineBuilder qty(@NonNull final BigDecimal qty)
{
if (productId == null)
{
throw new AdempiereException("Setting BigDecimal Qty not allowed if the product was not already set");
}
final I_C_UOM uom = productBL.getStockUOM(productId);
return qty(Quantity.of(qty, uom));
}
@Nullable
private UomId getUomId()
{
return qty != null ? qty.getUomId() : null;
}
public OrderLineBuilder priceUomId(@Nullable final UomId priceUomId)
{
assertNotBuilt();
this.priceUomId = priceUomId;
return this;
}
public OrderLineBuilder externalId(@Nullable final ExternalId externalId)
{
assertNotBuilt();
this.externalId = externalId;
return this;
}
public OrderLineBuilder manualPrice(@Nullable final BigDecimal manualPrice) | {
assertNotBuilt();
this.manualPrice = manualPrice;
return this;
}
public OrderLineBuilder manualPrice(@Nullable final Money manualPrice)
{
return manualPrice(manualPrice != null ? manualPrice.toBigDecimal() : null);
}
public OrderLineBuilder manualDiscount(final BigDecimal manualDiscount)
{
assertNotBuilt();
this.manualDiscount = manualDiscount;
return this;
}
public OrderLineBuilder setDimension(final Dimension dimension)
{
assertNotBuilt();
this.dimension = dimension;
return this;
}
public boolean isProductAndUomMatching(@Nullable final ProductId productId, @Nullable final UomId uomId)
{
return ProductId.equals(getProductId(), productId)
&& UomId.equals(getUomId(), uomId);
}
public OrderLineBuilder description(@Nullable final String description)
{
this.description = description;
return this;
}
public OrderLineBuilder hideWhenPrinting(final boolean hideWhenPrinting)
{
this.hideWhenPrinting = hideWhenPrinting;
return this;
}
public OrderLineBuilder details(@NonNull final Collection<OrderLineDetailCreateRequest> details)
{
assertNotBuilt();
detailCreateRequests.addAll(details);
return this;
}
public OrderLineBuilder detail(@NonNull final OrderLineDetailCreateRequest detail)
{
assertNotBuilt();
detailCreateRequests.add(detail);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLineBuilder.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// onParts ////////////////////////////////////////////////////////////
public List<CmmnOnPartDeclaration> getOnParts() {
return onParts;
}
public List<CmmnOnPartDeclaration> getOnParts(String sourceId) {
return onPartMap.get(sourceId);
}
public void addOnPart(CmmnOnPartDeclaration onPart) {
CmmnActivity source = onPart.getSource();
if (source == null) {
// do nothing: ignore onPart
return;
}
String sourceId = source.getId();
List<CmmnOnPartDeclaration> onPartDeclarations = onPartMap.get(sourceId);
if (onPartDeclarations == null) {
onPartDeclarations = new ArrayList<CmmnOnPartDeclaration>();
onPartMap.put(sourceId, onPartDeclarations);
}
for (CmmnOnPartDeclaration onPartDeclaration : onPartDeclarations) {
if (onPart.getStandardEvent().equals(onPartDeclaration.getStandardEvent())) {
// if there already exists an onPartDeclaration which has the
// same defined standardEvent then ignore this onPartDeclaration.
if (onPartDeclaration.getSentry() == onPart.getSentry()) {
return;
}
// but merge the sentryRef into the already existing onPartDeclaration
if (onPartDeclaration.getSentry() == null && onPart.getSentry() != null) {
// According to the specification, when "sentryRef" is specified,
// "standardEvent" must have value "exit" (page 39, Table 23).
// But there is no further check necessary.
onPartDeclaration.setSentry(onPart.getSentry());
return;
}
}
}
onPartDeclarations.add(onPart);
onParts.add(onPart); | }
// variableOnParts
public void addVariableOnParts(CmmnVariableOnPartDeclaration variableOnPartDeclaration) {
variableOnParts.add(variableOnPartDeclaration);
}
public boolean hasVariableOnPart(String variableEventName, String variableName) {
for(CmmnVariableOnPartDeclaration variableOnPartDeclaration: variableOnParts) {
if(variableOnPartDeclaration.getVariableEvent().equals(variableEventName) &&
variableOnPartDeclaration.getVariableName().equals(variableName)) {
return true;
}
}
return false;
}
public List<CmmnVariableOnPartDeclaration> getVariableOnParts() {
return variableOnParts;
}
// ifPart //////////////////////////////////////////////////////////////////
public CmmnIfPartDeclaration getIfPart() {
return ifPart;
}
public void setIfPart(CmmnIfPartDeclaration ifPart) {
this.ifPart = ifPart;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CmmnSentryDeclaration.java | 1 |
请完成以下Java代码 | public static int toInt(@NonNull final Duration duration, @NonNull final TemporalUnit unit)
{
return (int)toLong(duration, unit);
}
public static long toLong(@NonNull final Duration duration, @NonNull final TemporalUnit unit)
{
if (unit == ChronoUnit.SECONDS)
{
return duration.getSeconds();
}
else if (unit == ChronoUnit.MINUTES)
{
return duration.toMinutes();
}
else if (unit == ChronoUnit.HOURS)
{
return duration.toHours();
}
else if (unit == ChronoUnit.DAYS)
{
return duration.toDays();
}
else
{
throw Check.newException("Cannot convert " + duration + " to " + unit);
}
}
private static BigDecimal getEquivalentInSmallerTemporalUnit(@NonNull final BigDecimal durationBD, @NonNull final TemporalUnit unit)
{
if (unit == ChronoUnit.DAYS)
{
return durationBD.multiply(BigDecimal.valueOf(WORK_HOURS_PER_DAY));// This refers to work hours, not calendar hours
}
if (unit == ChronoUnit.HOURS)
{
return durationBD.multiply(BigDecimal.valueOf(60));
}
if (unit == ChronoUnit.MINUTES)
{ | return durationBD.multiply(BigDecimal.valueOf(60));
}
if (unit == ChronoUnit.SECONDS)
{
return durationBD.multiply(BigDecimal.valueOf(1000));
}
throw Check.newException("No smaller temporal unit defined for {}", unit);
}
public static boolean isCompleteDays(@NonNull final Duration duration)
{
if (duration.isZero())
{
return true;
}
final Duration daysAsDuration = Duration.ofDays(duration.toDays());
return daysAsDuration.equals(duration);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\DurationUtils.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=3145guofu
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
logging.level.com.gf.map | per=debug
spring.redis.host=127.0.0.1
debug=true
fastjson.parser.autoTypeAccept=com.gf. | repos\SpringBootLearning-master (1)\springboot-cache\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public String getTextValue() {
return node.path("textValue").stringValue(null);
}
@Override
public void setTextValue(String textValue) {
throw new UnsupportedOperationException("Not supported to set text value");
}
@Override
public String getTextValue2() {
return node.path("textValues").stringValue(null);
}
@Override
public void setTextValue2(String textValue2) {
throw new UnsupportedOperationException("Not supported to set text value2");
}
@Override
public Long getLongValue() {
JsonNode longNode = node.path("longValue");
if (longNode.isNumber()) {
return longNode.longValue();
}
return null;
}
@Override
public void setLongValue(Long longValue) {
throw new UnsupportedOperationException("Not supported to set long value");
}
@Override
public Double getDoubleValue() {
JsonNode doubleNode = node.path("doubleValue");
if (doubleNode.isNumber()) {
return doubleNode.doubleValue();
}
return null;
}
@Override
public void setDoubleValue(Double doubleValue) { | throw new UnsupportedOperationException("Not supported to set double value");
}
@Override
public byte[] getBytes() {
throw new UnsupportedOperationException("Not supported to get bytes");
}
@Override
public void setBytes(byte[] bytes) {
throw new UnsupportedOperationException("Not supported to set bytes");
}
@Override
public Object getCachedValue() {
throw new UnsupportedOperationException("Not supported to set get cached value");
}
@Override
public void setCachedValue(Object cachedValue) {
throw new UnsupportedOperationException("Not supported to set cached value");
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delete\BatchDeleteCaseConfig.java | 1 |
请完成以下Java代码 | public void setTaxAmtInfo (final @Nullable BigDecimal TaxAmtInfo)
{
set_Value (COLUMNNAME_TaxAmtInfo, TaxAmtInfo);
}
@Override
public BigDecimal getTaxAmtInfo()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtInfo);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void settaxfree (final boolean taxfree)
{
set_Value (COLUMNNAME_taxfree, taxfree);
}
@Override
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
@Override
public void setUPC_CU (final @Nullable java.lang.String UPC_CU)
{
set_ValueNoCheck (COLUMNNAME_UPC_CU, UPC_CU);
}
@Override | public java.lang.String getUPC_CU()
{
return get_ValueAsString(COLUMNNAME_UPC_CU);
}
@Override
public void setUPC_TU (final @Nullable java.lang.String UPC_TU)
{
set_ValueNoCheck (COLUMNNAME_UPC_TU, UPC_TU);
}
@Override
public java.lang.String getUPC_TU()
{
return get_ValueAsString(COLUMNNAME_UPC_TU);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_500_v.java | 1 |
请完成以下Java代码 | public class AlarmNotificationInfo implements RuleOriginatedNotificationInfo {
private String alarmType;
private String action;
private UUID alarmId;
private EntityId alarmOriginator;
private String alarmOriginatorName;
private String alarmOriginatorLabel;
private AlarmSeverity alarmSeverity;
private AlarmStatus alarmStatus;
private boolean acknowledged;
private boolean cleared;
private CustomerId alarmCustomerId;
private DashboardId dashboardId;
private Map<String, String> details;
@Override
public Map<String, String> getTemplateData() {
Map<String, String> templateData = details != null ? new HashMap<>(details) : new HashMap<>();
templateData.put("alarmType", alarmType);
templateData.put("action", action);
templateData.put("alarmId", alarmId.toString());
templateData.put("alarmSeverity", alarmSeverity.name().toLowerCase());
templateData.put("alarmStatus", alarmStatus.toString()); | templateData.put("alarmOriginatorEntityType", alarmOriginator.getEntityType().getNormalName());
templateData.put("alarmOriginatorName", alarmOriginatorName);
templateData.put("alarmOriginatorLabel", alarmOriginatorLabel);
templateData.put("alarmOriginatorId", alarmOriginator.getId().toString());
return templateData;
}
@Override
public CustomerId getAffectedCustomerId() {
return alarmCustomerId;
}
@Override
public EntityId getStateEntityId() {
return alarmOriginator;
}
@Override
public DashboardId getDashboardId() {
return dashboardId;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\info\AlarmNotificationInfo.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.