instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
private String username;
private String password;
private Server server;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() { | return password;
}
public void setPassword(String password) {
this.password = password;
}
public Server getServer() {
return server;
}
public void setServer(Server server) {
this.server = server;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-autoconfiguration\src\main\java\com\baeldung\autoconfiguration\annotationprocessor\DatabaseProperties.java | 2 |
请完成以下Java代码 | public ProcessEngineConfiguration setPasswordPolicy(PasswordPolicy passwordPolicy) {
this.passwordPolicy = passwordPolicy;
return this;
}
public boolean isEnableCmdExceptionLogging() {
return enableCmdExceptionLogging;
}
public ProcessEngineConfiguration setEnableCmdExceptionLogging(boolean enableCmdExceptionLogging) {
this.enableCmdExceptionLogging = enableCmdExceptionLogging;
return this;
}
public boolean isEnableReducedJobExceptionLogging() {
return enableReducedJobExceptionLogging;
}
public ProcessEngineConfiguration setEnableReducedJobExceptionLogging(boolean enableReducedJobExceptionLogging) {
this.enableReducedJobExceptionLogging = enableReducedJobExceptionLogging;
return this;
}
public String getDeserializationAllowedClasses() {
return deserializationAllowedClasses;
}
public ProcessEngineConfiguration setDeserializationAllowedClasses(String deserializationAllowedClasses) {
this.deserializationAllowedClasses = deserializationAllowedClasses;
return this;
}
public String getDeserializationAllowedPackages() {
return deserializationAllowedPackages;
}
public ProcessEngineConfiguration setDeserializationAllowedPackages(String deserializationAllowedPackages) {
this.deserializationAllowedPackages = deserializationAllowedPackages;
return this;
}
public DeserializationTypeValidator getDeserializationTypeValidator() {
return deserializationTypeValidator;
}
public ProcessEngineConfiguration setDeserializationTypeValidator(DeserializationTypeValidator deserializationTypeValidator) {
this.deserializationTypeValidator = deserializationTypeValidator;
return this;
} | public boolean isDeserializationTypeValidationEnabled() {
return deserializationTypeValidationEnabled;
}
public ProcessEngineConfiguration setDeserializationTypeValidationEnabled(boolean deserializationTypeValidationEnabled) {
this.deserializationTypeValidationEnabled = deserializationTypeValidationEnabled;
return this;
}
public String getInstallationId() {
return installationId;
}
public ProcessEngineConfiguration setInstallationId(String installationId) {
this.installationId = installationId;
return this;
}
public boolean isSkipOutputMappingOnCanceledActivities() {
return skipOutputMappingOnCanceledActivities;
}
public void setSkipOutputMappingOnCanceledActivities(boolean skipOutputMappingOnCanceledActivities) {
this.skipOutputMappingOnCanceledActivities = skipOutputMappingOnCanceledActivities;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\ProcessEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static List getList() {
List strList = new ArrayList();
InputStreamReader read = null;
BufferedReader reader = null;
try {
read = new InputStreamReader(new ClassPathResource("WxCityNo.txt").getInputStream(), "utf-8");
reader = new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null) {
Map<String, String> strMap = new HashMap<>();
strMap.put("name", line.substring(0, line.indexOf("=")));
strMap.put("desc", line.substring(line.indexOf("=") + 1));
strList.add(strMap);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read != null) {
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close(); | } catch (IOException e) {
e.printStackTrace();
}
}
}
return strList;
}
public static String getCityNameByNo(String cityNo) {
List list = getList();
String cityName = null;
for (int i = 0; i < list.size(); i++) {
Map map = (HashMap) list.get(i);
if (cityNo.equals(map.get("name"))) {
cityName = (String) map.get("desc");
}
}
return cityName;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\banklink\utils\weixin\WxCityNo.java | 2 |
请完成以下Java代码 | public void runSQLAfterAllImport()
{
final List<DBFunction> functions = dbFunctions.getAvailableAfterAllFunctions();
if (functions.isEmpty())
{
return;
}
final DataImportRunId dataImportRunId = getDataImportRunIdOfImportedRecords();
functions.forEach(function -> {
try
{
DBFunctionHelper.doDBFunctionCall(function, dataImportRunId);
}
catch (Exception ex)
{
final AdempiereException metasfreshEx = AdempiereException.wrapIfNeeded(ex);
final AdIssueId issueId = errorManager.createIssue(metasfreshEx);
loggable.addLog("Failed running " + function + ": " + AdempiereException.extractMessage(metasfreshEx) + " (AD_Issue_ID=" + issueId.getRepoId() + ")");
throw metasfreshEx;
}
});
}
private DataImportRunId getDataImportRunIdOfImportedRecords()
{
final ImportRecordsSelection selection = getSelection();
final String importTableName = selection.getImportTableName();
return DataImportRunId.ofRepoIdOrNull(
DB.getSQLValueEx(
ITrx.TRXNAME_ThreadInherited, | "SELECT " + ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID
+ " FROM " + importTableName
+ " WHERE " + ImportTableDescriptor.COLUMNNAME_I_IsImported + "='Y' "
+ " " + selection.toSqlWhereClause(importTableName)
)
);
}
private Optional<DataImportConfigId> extractDataImportConfigId(@NonNull final ImportRecordType importRecord)
{
if (tableDescriptor.getDataImportConfigIdColumnName() == null)
{
return Optional.empty();
}
final Optional<Integer> value = InterfaceWrapperHelper.getValue(importRecord, tableDescriptor.getDataImportConfigIdColumnName());
return value.map(DataImportConfigId::ofRepoIdOrNull);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\SqlImportSource.java | 1 |
请完成以下Java代码 | public int getM_ShipmentSchedule_ExportAudit_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID);
}
@Override
public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule()
{
return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class);
}
@Override
public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule)
{
set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule);
}
@Override
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
} | @Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI)
{
throw new IllegalArgumentException ("TransactionIdAPI is virtual column"); }
@Override
public java.lang.String getTransactionIdAPI()
{
return get_ValueAsString(COLUMNNAME_TransactionIdAPI);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit_Item.java | 1 |
请完成以下Java代码 | public class MutexLock implements Lock {
// 使用静态内部类的方式来自定义同步器,隔离使用者和实现者
static class Sync extends AbstractQueuedSynchronizer {
// 我们定义状态标志位是1时表示获取到了锁,为0时表示没有获取到锁
@Override
protected boolean tryAcquire(int arg) {
// 获取锁有竞争所以需要使用CAS原子操作
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
@Override
protected boolean tryRelease(int arg) {
// 只有获取到锁的线程才会解锁,所以这里没有竞争,直接使用setState方法在来改变同步状态
setState(0);
setExclusiveOwnerThread(null);
return true;
}
@Override
protected boolean isHeldExclusively() {
// 如果货物到锁,当前线程独占
return getState() == 1;
}
// 返回一个Condition,每个condition都包含了一个condition队列
Condition newCondition() {
return new ConditionObject();
}
}
// 仅需要将操作代理到Sync上即可
private final Sync sync = new Sync();
@Override
public void lock() {
sync.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryRelease(1);
}
@Override | public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.release(0);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
public static void main(String[] args) {
MutexLock lock = new MutexLock();
final User user = new User();
for (int i = 0; i < 100; i++) {
new Thread(() -> {
lock.lock();
try {
user.setAge(user.getAge() + 1);
System.out.println(user.getAge());
} finally {
lock.unlock();
}
}).start();
}
}
} | repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\MutexLock.java | 1 |
请完成以下Java代码 | public class MethodInvocationPrivilegeEvaluator implements InitializingBean {
protected static final Log logger = LogFactory.getLog(MethodInvocationPrivilegeEvaluator.class);
@SuppressWarnings("NullAway.Init")
private @Nullable AbstractSecurityInterceptor securityInterceptor;
@Override
public void afterPropertiesSet() {
Assert.notNull(this.securityInterceptor, "SecurityInterceptor required");
}
public boolean isAllowed(MethodInvocation invocation, Authentication authentication) {
Assert.notNull(invocation, "MethodInvocation required");
Assert.notNull(invocation.getMethod(), "MethodInvocation must provide a non-null getMethod()");
Collection<ConfigAttribute> attrs = this.securityInterceptor.obtainSecurityMetadataSource()
.getAttributes(invocation);
if (attrs == null) {
return !this.securityInterceptor.isRejectPublicInvocations();
}
if (authentication == null || authentication.getAuthorities().isEmpty()) {
return false; | }
try {
this.securityInterceptor.getAccessDecisionManager().decide(authentication, invocation, attrs);
return true;
}
catch (AccessDeniedException unauthorized) {
logger.debug(LogMessage.format("%s denied for %s", invocation, authentication), unauthorized);
return false;
}
}
public void setSecurityInterceptor(AbstractSecurityInterceptor securityInterceptor) {
Assert.notNull(securityInterceptor, "AbstractSecurityInterceptor cannot be null");
Assert.isTrue(MethodInvocation.class.equals(securityInterceptor.getSecureObjectClass()),
"AbstractSecurityInterceptor does not support MethodInvocations");
Assert.notNull(securityInterceptor.getAccessDecisionManager(),
"AbstractSecurityInterceptor must provide a non-null AccessDecisionManager");
this.securityInterceptor = securityInterceptor;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\MethodInvocationPrivilegeEvaluator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FTSConfigService
{
private final IESSystem esSystem = Services.get(IESSystem.class);
private final FTSConfigRepository ftsConfigRepository;
private final FTSFilterDescriptorRepository ftsFilterDescriptorRepository;
public FTSConfigService(
@NonNull final FTSConfigRepository ftsConfigRepository,
@NonNull final FTSFilterDescriptorRepository ftsFilterDescriptorRepository)
{
this.ftsConfigRepository = ftsConfigRepository;
this.ftsFilterDescriptorRepository = ftsFilterDescriptorRepository;
}
public BooleanWithReason getEnabled()
{
return esSystem.getEnabled();
}
public RestHighLevelClient elasticsearchClient()
{
return esSystem.elasticsearchClient();
}
public void addListener(@NonNull final FTSConfigChangedListener listener) { ftsConfigRepository.addListener(listener); }
public FTSConfig getConfigByESIndexName(@NonNull final String esIndexName) { return ftsConfigRepository.getByESIndexName(esIndexName); }
public FTSConfig getConfigById(@NonNull final FTSConfigId ftsConfigId) { return ftsConfigRepository.getConfigById(ftsConfigId); }
public FTSConfigSourceTablesMap getSourceTables() | {
return ftsConfigRepository.getSourceTables();
}
public Optional<FTSFilterDescriptor> getFilterByTargetTableName(@NonNull final String targetTableName)
{
return ftsFilterDescriptorRepository.getByTargetTableName(targetTableName);
}
public FTSFilterDescriptor getFilterById(@NonNull final FTSFilterDescriptorId id)
{
return ftsFilterDescriptorRepository.getById(id);
}
public void updateConfigFields(@NonNull final I_ES_FTS_Config record)
{
final FTSConfigId configId = FTSConfigId.ofRepoId(record.getES_FTS_Config_ID());
final Set<ESFieldName> esFieldNames = ESDocumentToIndexTemplate.ofJsonString(record.getES_DocumentToIndexTemplate()).getESFieldNames();
ftsConfigRepository.setConfigFields(configId, esFieldNames);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSConfigService.java | 2 |
请完成以下Java代码 | public int getM_DistributionRun_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionRun_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_DistributionRun_ID()));
}
/** Set Distribution Run Line.
@param M_DistributionRunLine_ID
Distribution Run Lines define Distribution List, the Product and Quantiries
*/
public void setM_DistributionRunLine_ID (int M_DistributionRunLine_ID)
{
if (M_DistributionRunLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionRunLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionRunLine_ID, Integer.valueOf(M_DistributionRunLine_ID));
}
/** Get Distribution Run Line.
@return Distribution Run Lines define Distribution List, the Product and Quantiries
*/
public int getM_DistributionRunLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionRunLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Minimum Quantity.
@param MinQty
Minimum quantity for the business partner
*/
public void setMinQty (BigDecimal MinQty)
{
set_Value (COLUMNNAME_MinQty, MinQty);
}
/** Get Minimum Quantity.
@return Minimum quantity for the business partner
*/
public BigDecimal getMinQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinQty);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else | set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Total Quantity.
@param TotalQty
Total Quantity
*/
public void setTotalQty (BigDecimal TotalQty)
{
set_Value (COLUMNNAME_TotalQty, TotalQty);
}
/** Get Total Quantity.
@return Total Quantity
*/
public BigDecimal getTotalQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalQty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionRunLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void initRouteContext(final Exchange exchange)
{
final String clientValue = Util.resolveProperty(getContext(), AbstractEDIRoute.EDI_ORDER_ADClientValue);
final EcosioOrdersRouteContext context = EcosioOrdersRouteContext.builder()
.clientValue(clientValue)
.build();
exchange.setProperty(ROUTE_PROPERTY_ECOSIO_ORDER_ROUTE_CONTEXT, context);
}
private static void prepareNotifyReplicationTrxDone(@NonNull final Exchange exchange)
{
final EcosioOrdersRouteContext context = exchange.getProperty(ROUTE_PROPERTY_ECOSIO_ORDER_ROUTE_CONTEXT, EcosioOrdersRouteContext.class);
final List<NotifyReplicationTrxRequest> trxUpdateList = context.getImportedTrxName2TrxStatus()
.keySet()
.stream()
.map(context::getStatusRequestFor)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableList.toImmutableList());
exchange.getIn().setBody(trxUpdateList); | }
private static void setImportStatusOk(@NonNull final Exchange exchange)
{
final EcosioOrdersRouteContext context = exchange.getProperty(ROUTE_PROPERTY_ECOSIO_ORDER_ROUTE_CONTEXT, EcosioOrdersRouteContext.class);
context.setCurrentReplicationTrxStatus(EcosioOrdersRouteContext.TrxImportStatus.ok());
}
private static void setImportStatusError(@NonNull final Exchange exchange)
{
final EcosioOrdersRouteContext context = exchange.getProperty(ROUTE_PROPERTY_ECOSIO_ORDER_ROUTE_CONTEXT, EcosioOrdersRouteContext.class);
final String errorMsg = ExceptionUtil.extractErrorMessage(exchange);
context.setCurrentReplicationTrxStatus(EcosioOrdersRouteContext.TrxImportStatus.error(errorMsg));
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\ecosio\EcosioOrdersRoute.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getProcessingPriorityCode() {
return processingPriorityCode;
}
/**
* Sets the value of the processingPriorityCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProcessingPriorityCode(String value) {
this.processingPriorityCode = value;
}
/**
* Gets the value of the ackRequest property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAckRequest() {
return ackRequest;
}
/**
* Sets the value of the ackRequest property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAckRequest(String value) {
this.ackRequest = value;
}
/**
* Gets the value of the agreementId property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getAgreementId() {
return agreementId;
}
/**
* Sets the value of the agreementId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAgreementId(String value) {
this.agreementId = value;
}
/**
* Gets the value of the testIndicator property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTestIndicator() {
return testIndicator;
}
/**
* Sets the value of the testIndicator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTestIndicator(String value) {
this.testIndicator = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\InterchangeHeaderType.java | 2 |
请完成以下Java代码 | public void updateData(
@NonNull final AttachmentEntryId attachmentEntryId,
final byte[] data)
{
attachmentEntryRepository.updateAttachmentEntryData(attachmentEntryId, data);
}
@NonNull
public Stream<EmailAttachment> streamEmailAttachments(@NonNull final TableRecordReference recordRef, @Nullable final String tagName)
{
return attachmentEntryRepository.getByReferencedRecord(recordRef)
.stream()
.filter(attachmentEntry -> Check.isBlank(tagName) || attachmentEntry.getTags().hasTag(tagName))
.map(attachmentEntry -> EmailAttachment.builder()
.filename(attachmentEntry.getFilename())
.attachmentDataSupplier(() -> retrieveData(attachmentEntry.getId()))
.build());
}
/**
* Persist the given {@code attachmentEntry} as-is.
* Warning: e.g. tags or referenced records that are persisted before this method is called, but are not part of the given {@code attachmentEntry} are dropped.
*/
public void save(@NonNull final AttachmentEntry attachmentEntry)
{
attachmentEntryRepository.save(attachmentEntry);
}
@Value
public static class AttachmentEntryQuery
{
List<String> tagsSetToTrue;
List<String> tagsSetToAnyValue; | Object referencedRecord;
String mimeType;
@Builder
private AttachmentEntryQuery(
@Singular("tagSetToTrue") final List<String> tagsSetToTrue,
@Singular("tagSetToAnyValue") final List<String> tagsSetToAnyValue,
@Nullable final String mimeType,
@NonNull final Object referencedRecord)
{
this.referencedRecord = referencedRecord;
this.mimeType = mimeType;
this.tagsSetToTrue = tagsSetToTrue;
this.tagsSetToAnyValue = tagsSetToAnyValue;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryService.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(values.get(this))
.toString();
}
@Override
public DocumentId getId()
{
return rowId;
}
public ClientAndOrgId getClientAndOrgId()
{
return clientAndOrgId;
}
@Override
public boolean isProcessed()
{
return false;
}
@Override
public DocumentPath getDocumentPath()
{
return null;
}
@Override
public Set<String> getFieldNames() | {
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
@Override
public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName()
{
return values.getViewEditorRenderModeByFieldName();
}
public BPartnerId getBPartnerId()
{
return bpartner.getIdAs(BPartnerId::ofRepoId);
}
public InvoiceRow withPreparedForAllocationSet() { return withPreparedForAllocation(true); }
public InvoiceRow withPreparedForAllocationUnset() { return withPreparedForAllocation(false); }
public InvoiceRow withPreparedForAllocation(final boolean isPreparedForAllocation)
{
return this.isPreparedForAllocation != isPreparedForAllocation
? toBuilder().isPreparedForAllocation(isPreparedForAllocation).build()
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static RecordChangeLog createBankAccountChangeLog(
@NonNull final I_C_BP_BankAccount bankAccountRecord,
@NonNull final CompositeRelatedRecords relatedRecords)
{
final ImmutableListMultimap<TableRecordReference, RecordChangeLogEntry> recordRef2LogEntries = relatedRecords.getRecordRef2LogEntries();
final ImmutableList<RecordChangeLogEntry> userEntries = recordRef2LogEntries.get(TableRecordReference.of(bankAccountRecord));
IPair<Instant, UserId> lastChanged = ImmutablePair.of(
TimeUtil.asInstant(bankAccountRecord.getUpdated()),
UserId.ofRepoIdOrNull(bankAccountRecord.getUpdatedBy()/* might be -1 */));
final List<RecordChangeLogEntry> domainEntries = new ArrayList<>();
for (final RecordChangeLogEntry userEntry : userEntries)
{
final Optional<RecordChangeLogEntry> entry = entryWithDomainFieldName(userEntry, C_BP_BANKACCOUNT_COLUMN_MAP);
lastChanged = latestOf(entry, lastChanged);
entry.ifPresent(domainEntries::add);
}
return RecordChangeLog.builder()
.createdByUserId(UserId.ofRepoIdOrNull(bankAccountRecord.getCreatedBy()/* might be -1 */))
.createdTimestamp(TimeUtil.asInstant(bankAccountRecord.getCreated()))
.lastChangedByUserId(lastChanged.getRight())
.lastChangedTimestamp(lastChanged.getLeft())
.recordId(ComposedRecordId.singleKey(I_C_BP_BankAccount.COLUMNNAME_C_BP_BankAccount_ID, bankAccountRecord.getC_BP_BankAccount_ID()))
.tableName(I_C_BP_BankAccount.Table_Name)
.entries(domainEntries)
.build();
}
private static Optional<RecordChangeLogEntry> entryWithDomainFieldName(
@NonNull final RecordChangeLogEntry entry, | @NonNull final ImmutableMap<String, String> columnMap)
{
final String fieldName = columnMap.get(entry.getColumnName());
if (fieldName == null)
{
return Optional.empty();
}
final RecordChangeLogEntry result = entry
.toBuilder()
.columnName(columnMap.get(entry.getColumnName()))
.build();
return Optional.of(result);
}
private static IPair<Instant, UserId> latestOf(
@NonNull final Optional<RecordChangeLogEntry> currentLogEntry,
@NonNull final IPair<Instant, UserId> previousLastChanged)
{
if (!currentLogEntry.isPresent())
{
return previousLastChanged;
}
final Instant entryTimestamp = currentLogEntry.get().getChangedTimestamp();
if (previousLastChanged.getLeft().isAfter(entryTimestamp))
{
return previousLastChanged;
}
return ImmutablePair.of(entryTimestamp, currentLogEntry.get().getChangedByUserId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\repository\ChangeLogUtil.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class ViewProfileId
{
public static final ViewProfileId NULL = null;
public static boolean isNull(final ViewProfileId profileId)
{
return profileId == null || Objects.equals(profileId, NULL);
}
@JsonCreator
public static final ViewProfileId fromJson(final String profileIdStr)
{
if (profileIdStr == null)
{
return NULL;
}
final String profileIdStrNorm = profileIdStr.trim();
if (profileIdStrNorm.isEmpty())
{
return NULL; | }
return new ViewProfileId(profileIdStrNorm);
}
private final String id;
private ViewProfileId(@NonNull final String id)
{
this.id = id;
}
@JsonValue
public String toJson()
{
return id;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewProfileId.java | 2 |
请完成以下Java代码 | public void setRate (final @Nullable BigDecimal Rate)
{
set_Value (COLUMNNAME_Rate, Rate);
}
@Override
public BigDecimal getRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSupplier_GTIN_CU (final @Nullable java.lang.String Supplier_GTIN_CU)
{
set_ValueNoCheck (COLUMNNAME_Supplier_GTIN_CU, Supplier_GTIN_CU);
}
@Override
public java.lang.String getSupplier_GTIN_CU()
{
return get_ValueAsString(COLUMNNAME_Supplier_GTIN_CU);
}
@Override
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 |
请在Spring Boot框架中完成以下Java代码 | public String getResponse() {
return response;
}
/** 返回信息 **/
public void setResponse(String response) {
this.response = response == null ? null : response.trim();
}
/** 商户编号 **/
public String getMerchantNo() {
return merchantNo;
}
/** 商户编号 **/
public void setMerchantNo(String merchantNo) {
this.merchantNo = merchantNo == null ? null : merchantNo.trim();
}
/** 商户订单号 **/ | public String getMerchantOrderNo() {
return merchantOrderNo;
}
/** 商户订单号 **/
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo == null ? null : merchantOrderNo.trim();
}
/** HTTP状态 **/
public Integer getHttpStatus() {
return httpStatus;
}
/** HTTP状态 **/
public void setHttpStatus(Integer httpStatus) {
this.httpStatus = httpStatus;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpNotifyRecordLog.java | 2 |
请完成以下Java代码 | protected String getStencilId(BaseElement baseElement) {
EndEvent endEvent = (EndEvent) baseElement;
List<EventDefinition> eventDefinitions = endEvent.getEventDefinitions();
if (eventDefinitions.size() != 1) {
return STENCIL_EVENT_END_NONE;
}
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof ErrorEventDefinition) {
return STENCIL_EVENT_END_ERROR;
} else if (eventDefinition instanceof CancelEventDefinition) {
return STENCIL_EVENT_END_CANCEL;
} else if (eventDefinition instanceof TerminateEventDefinition) {
return STENCIL_EVENT_END_TERMINATE;
} else {
return STENCIL_EVENT_END_NONE;
}
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
EndEvent endEvent = (EndEvent) baseElement;
addEventProperties(endEvent, propertiesNode);
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
EndEvent endEvent = new EndEvent();
String stencilId = BpmnJsonConverterUtil.getStencilId(elementNode);
if (STENCIL_EVENT_END_ERROR.equals(stencilId)) {
convertJsonToErrorDefinition(elementNode, endEvent);
} else if (STENCIL_EVENT_END_CANCEL.equals(stencilId)) {
CancelEventDefinition eventDefinition = new CancelEventDefinition();
endEvent.getEventDefinitions().add(eventDefinition); | } else if (STENCIL_EVENT_END_TERMINATE.equals(stencilId)) {
TerminateEventDefinition eventDefinition = new TerminateEventDefinition();
String terminateAllStringValue = getPropertyValueAsString(PROPERTY_TERMINATE_ALL, elementNode);
if (StringUtils.isNotEmpty(terminateAllStringValue)) {
eventDefinition.setTerminateAll("true".equals(terminateAllStringValue));
}
String terminateMiStringValue = getPropertyValueAsString(PROPERTY_TERMINATE_MULTI_INSTANCE, elementNode);
if (StringUtils.isNotEmpty(terminateMiStringValue)) {
eventDefinition.setTerminateMultiInstance("true".equals(terminateMiStringValue));
}
endEvent.getEventDefinitions().add(eventDefinition);
}
return endEvent;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\EndEventJsonConverter.java | 1 |
请完成以下Java代码 | public QualityInspectionLineType getQualityInspectionLineType()
{
return qualityInspectionLineType;
}
@Override
public void setQualityInspectionLineType(final QualityInspectionLineType qualityInspectionLineType)
{
this.qualityInspectionLineType = qualityInspectionLineType;
}
@Override
public String getProductionMaterialType()
{
return productionMaterialType;
}
@Override
public void setProductionMaterialType(final String productionMaterialType)
{
this.productionMaterialType = productionMaterialType;
}
@Override
public I_M_Product getM_Product()
{
return product;
}
@Override
public void setM_Product(final I_M_Product product)
{
this.product = product;
}
@Override
public String getName()
{
return name;
}
@Override
public void setName(final String name)
{
this.name = name;
}
@Override
public I_C_UOM getC_UOM()
{
return uom;
}
@Override
public void setC_UOM(final I_C_UOM uom)
{
this.uom = uom;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public void setQty(final BigDecimal qty)
{
this.qty = qty;
}
@Override
public BigDecimal getQtyProjected()
{
return qtyProjected;
}
@Override
public void setQtyProjected(final BigDecimal qtyProjected)
{
this.qtyProjected = qtyProjected;
}
@Override
public BigDecimal getPercentage()
{
return percentage;
}
@Override
public void setPercentage(final BigDecimal percentage)
{
this.percentage = percentage;
}
@Override
public boolean isNegateQtyInReport()
{ | return negateQtyInReport;
}
@Override
public void setNegateQtyInReport(final boolean negateQtyInReport)
{
this.negateQtyInReport = negateQtyInReport;
}
@Override
public String getComponentType()
{
return componentType;
}
@Override
public void setComponentType(final String componentType)
{
this.componentType = componentType;
}
@Override
public String getVariantGroup()
{
return variantGroup;
}
@Override
public void setVariantGroup(final String variantGroup)
{
this.variantGroup = variantGroup;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
@Override
public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
this.handlingUnitsInfo = handlingUnitsInfo;
}
@Override
public void setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo)
{
handlingUnitsInfoProjected = handlingUnitsInfo;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfoProjected()
{
return handlingUnitsInfoProjected;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLine.java | 1 |
请完成以下Java代码 | public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getImplementationType() {
return implementationType;
}
public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public String getOnTransaction() {
return onTransaction;
}
public void setOnTransaction(String onTransaction) {
this.onTransaction = onTransaction;
}
public String getCustomPropertiesResolverImplementationType() {
return customPropertiesResolverImplementationType;
}
public void setCustomPropertiesResolverImplementationType(String customPropertiesResolverImplementationType) {
this.customPropertiesResolverImplementationType = customPropertiesResolverImplementationType;
} | public String getCustomPropertiesResolverImplementation() {
return customPropertiesResolverImplementation;
}
public void setCustomPropertiesResolverImplementation(String customPropertiesResolverImplementation) {
this.customPropertiesResolverImplementation = customPropertiesResolverImplementation;
}
public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance;
}
public ActivitiListener clone() {
ActivitiListener clone = new ActivitiListener();
clone.setValues(this);
return clone;
}
public void setValues(ActivitiListener otherListener) {
setEvent(otherListener.getEvent());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ActivitiListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Class<? extends SuspendedJobEntity> getManagedEntityClass() {
return SuspendedJobEntityImpl.class;
}
@Override
public SuspendedJobEntity create() {
return new SuspendedJobEntityImpl();
}
@Override
public SuspendedJobEntity findJobByCorrelationId(String correlationId) {
return getEntity("selectSuspendedJobByCorrelationId", correlationId, suspendedJobByCorrelationIdMatcher, true);
}
@Override
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(SuspendedJobQueryImpl jobQuery) {
String query = "selectSuspendedJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery);
}
@Override
public long findJobCountByQueryCriteria(SuspendedJobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectSuspendedJobCountByQueryCriteria", jobQuery);
}
@Override
public List<SuspendedJobEntity> findJobsByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
// If the execution has been inserted in the same command execution as this query, there can't be any in the database
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
return getListFromCache(suspendedJobsByExecutionIdMatcher, executionId);
} | return getList(dbSqlSession, "selectSuspendedJobsByExecutionId", executionId, suspendedJobsByExecutionIdMatcher, true);
}
@Override
@SuppressWarnings("unchecked")
public List<SuspendedJobEntity> findJobsByProcessInstanceId(final String processInstanceId) {
return getDbSqlSession().selectList("selectSuspendedJobsByProcessInstanceId", processInstanceId);
}
@Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateSuspendedJobTenantIdForDeployment", params);
}
@Override
protected IdGenerator getIdGenerator() {
return jobServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisSuspendedJobDataManager.java | 2 |
请完成以下Java代码 | public Response getHeadersBackFromDigestAuthentication() {
// As the Digest authentication require some complex steps to work we'll simulate the process
// https://en.wikipedia.org/wiki/Digest_access_authentication#Example_with_explanation
if (headers.getHeaderString("authorization") == null) {
String authenticationRequired = "Digest " + REALM_KEY + "=\"" + REALM_VALUE + "\", " + QOP_KEY + "=\"" + QOP_VALUE + "\", " + NONCE_KEY + "=\"" + NONCE_VALUE + "\", " + OPAQUE_KEY + "=\"" + OPAQUE_VALUE + "\"";
return Response.status(Response.Status.UNAUTHORIZED)
.header("WWW-Authenticate", authenticationRequired)
.build();
} else {
return echoHeaders();
}
}
@GET
@Path("/events")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void getServerSentEvents(@Context SseEventSink eventSink, @Context Sse sse) {
OutboundSseEvent event = sse.newEventBuilder()
.name("echo-headers")
.data(String.class, headers.getHeaderString(AddHeaderOnRequestFilter.FILTER_HEADER_KEY)) | .build();
eventSink.send(event);
}
private Response echoHeaders() {
Response.ResponseBuilder responseBuilder = Response.noContent();
headers.getRequestHeaders()
.forEach((k, v) -> {
v.forEach(value -> responseBuilder.header(k, value));
});
return responseBuilder.build();
}
} | repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\EchoHeaders.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPredicates(List<PredicateProperties> predicates) {
this.predicates = predicates;
}
public List<FilterProperties> getFilters() {
return filters;
}
public void setFilters(List<FilterProperties> filters) {
this.filters = filters;
}
public @Nullable URI getUri() {
return uri;
}
public void setUri(URI uri) {
this.uri = uri;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public Map<String, Object> getMetadata() {
return metadata;
} | public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RouteProperties that = (RouteProperties) o;
return this.order == that.order && Objects.equals(this.id, that.id)
&& Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters)
&& Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata);
}
@Override
public int hashCode() {
return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order);
}
@Override
public String toString() {
return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters
+ ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + '}';
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\RouteProperties.java | 2 |
请完成以下Java代码 | public void setSalesRep_ID (final int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID);
}
@Override
public int getSalesRep_ID()
{
return get_ValueAsInt(COLUMNNAME_SalesRep_ID);
}
@Override
public void setSendEMail (final boolean SendEMail)
{
set_Value (COLUMNNAME_SendEMail, SendEMail);
}
@Override
public boolean isSendEMail()
{
return get_ValueAsBoolean(COLUMNNAME_SendEMail);
}
@Override
public void setTotalLines (final BigDecimal TotalLines)
{
set_ValueNoCheck (COLUMNNAME_TotalLines, TotalLines);
}
@Override
public BigDecimal getTotalLines()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLines);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public org.compiere.model.I_C_ElementValue getUser1()
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(final org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
@Override
public void setUser1_ID (final int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, User1_ID);
}
@Override
public int getUser1_ID()
{
return get_ValueAsInt(COLUMNNAME_User1_ID);
}
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(final org.compiere.model.I_C_ElementValue User2) | {
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
@Override
public void setUserFlag (final @Nullable java.lang.String UserFlag)
{
set_Value (COLUMNNAME_UserFlag, UserFlag);
}
@Override
public java.lang.String getUserFlag()
{
return get_ValueAsString(COLUMNNAME_UserFlag);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice.java | 1 |
请完成以下Java代码 | public void onStartup(ServletContext servletContext) {
this.servletContext = servletContext;
properties.getRestApi().getFetchAndLock().getInitParams().forEach(servletContext::setInitParameter);
String restApiPathPattern = applicationPath.getUrlMapping();
registerFilter("EmptyBodyFilter", EmptyBodyFilter.class, restApiPathPattern);
registerFilter("CacheControlFilter", CacheControlFilter.class, restApiPathPattern);
}
private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass, final String... urlPatterns) {
return registerFilter(filterName, filterClass, null, urlPatterns);
}
private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass, final Map<String, String> initParameters,
final String... urlPatterns) { | FilterRegistration filterRegistration = servletContext.getFilterRegistration(filterName);
if (filterRegistration == null) {
filterRegistration = servletContext.addFilter(filterName, filterClass);
filterRegistration.addMappingForUrlPatterns(DISPATCHER_TYPES, true, urlPatterns);
if (initParameters != null) {
filterRegistration.setInitParameters(initParameters);
}
log.debug("Filter {} for URL {} registered.", filterName, urlPatterns);
}
return filterRegistration;
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-rest\src\main\java\org\camunda\bpm\spring\boot\starter\rest\CamundaBpmRestInitializer.java | 1 |
请完成以下Spring Boot application配置 | spring:
redis:
host: localhost
# 连接超时时间(记得添加单位,Duration)
timeout: 10000ms
# Redis默认情况下有16个分片,这里配置具体使用的分片
# database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1ms
# 连接池中的最大空闲连接 默认 8
max-idle: 8
| # 连接池中的最小空闲连接 默认 0
min-idle: 0
cache:
# 一般来说是不用配置的,Spring Cache 会根据依赖的包自行装配
type: redis
logging:
level:
com.xkcoding: debug | repos\spring-boot-demo-master\demo-cache-redis\src\main\resources\application.yml | 2 |
请完成以下Java代码 | private JSONDocumentChangedWebSocketEvent createEvent(final EventKey key)
{
return JSONDocumentChangedWebSocketEvent.rootDocument(key.getWindowId(), key.getDocumentId());
}
public void staleRootDocument(final WindowId windowId, final DocumentId documentId)
{
staleRootDocument(windowId, documentId, false);
}
public void staleRootDocument(final WindowId windowId, final DocumentId documentId, final boolean markActiveTabStaled)
{
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.markRootDocumentAsStaled();
if (markActiveTabStaled)
{
event.markActiveTabStaled();
}
}
public void staleTabs(final WindowId windowId, final DocumentId documentId, final Set<DetailId> tabIds)
{
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.staleTabs(tabIds);
}
public void staleIncludedDocuments(final WindowId windowId, final DocumentId documentId, final DetailId tabId, final DocumentIdsSelection rowIds)
{
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.staleIncludedRows(tabId, rowIds);
}
public void mergeFrom(final WindowId windowId, final DocumentId documentId, final JSONIncludedTabInfo tabInfo)
{
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.addIncludedTabInfo(tabInfo);
}
public void mergeFrom(final JSONDocumentChangedWebSocketEventCollector from)
{
final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> fromEvents = from._events;
if (fromEvents == null || fromEvents.isEmpty())
{
return; | }
fromEvents.forEach(this::mergeFrom);
}
private void mergeFrom(final EventKey key, final JSONDocumentChangedWebSocketEvent from)
{
final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> events = this._events;
if (events == null)
{
throw new AdempiereException("already closed: " + this);
}
events.compute(key, (k, existingEvent) -> {
if (existingEvent == null)
{
return from.copy();
}
else
{
existingEvent.mergeFrom(from);
return existingEvent;
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEventCollector.java | 1 |
请完成以下Java代码 | protected void switchVersionOfJob(JobEntity jobEntity, ProcessDefinitionEntity newProcessDefinition, Map<String, String> jobDefinitionMapping) {
jobEntity.setProcessDefinitionId(newProcessDefinition.getId());
jobEntity.setDeploymentId(newProcessDefinition.getDeploymentId());
String newJobDefinitionId = jobDefinitionMapping.get(jobEntity.getJobDefinitionId());
jobEntity.setJobDefinitionId(newJobDefinitionId);
}
protected void switchVersionOfIncident(CommandContext commandContext, IncidentEntity incidentEntity, ProcessDefinitionEntity newProcessDefinition) {
incidentEntity.setProcessDefinitionId(newProcessDefinition.getId());
}
protected void validateAndSwitchVersionOfExecution(CommandContext commandContext, ExecutionEntity execution, ProcessDefinitionEntity newProcessDefinition) {
// check that the new process definition version contains the current activity
if (execution.getActivity() != null) {
String activityId = execution.getActivity().getId();
PvmActivity newActivity = newProcessDefinition.findActivity(activityId);
if (newActivity == null) {
throw new ProcessEngineException(
"The new process definition " +
"(key = '" + newProcessDefinition.getKey() + "') " + | "does not contain the current activity " +
"(id = '" + activityId + "') " +
"of the process instance " +
"(id = '" + processInstanceId + "').");
}
// clear cached activity so that outgoing transitions are refreshed
execution.setActivity(newActivity);
}
// switch the process instance to the new process definition version
execution.setProcessDefinition(newProcessDefinition);
// and change possible existing tasks (as the process definition id is stored there too)
List<TaskEntity> tasks = commandContext.getTaskManager().findTasksByExecutionId(execution.getId());
for (TaskEntity taskEntity : tasks) {
taskEntity.setProcessDefinitionId(newProcessDefinition.getId());
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetProcessDefinitionVersionCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public User getUser(String username,String password) {
Query query = sessionFactory.getCurrentSession().createQuery("from CUSTOMER where username = :username");
query.setParameter("username",username);
try {
User user = (User) query.getSingleResult();
System.out.println(user.getPassword());
if(password.equals(user.getPassword())) {
return user;
}else {
return new User();
}
}catch(Exception e){
System.out.println(e.getMessage());
User user = new User();
return user;
}
}
@Transactional
public boolean userExists(String username) {
Query query = sessionFactory.getCurrentSession().createQuery("from CUSTOMER where username = :username"); | query.setParameter("username",username);
return !query.getResultList().isEmpty();
}
@Transactional
public User getUserByUsername(String username) {
Query<User> query = sessionFactory.getCurrentSession().createQuery("from User where username = :username", User.class);
query.setParameter("username", username);
try {
return query.getSingleResult();
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\dao\userDao.java | 2 |
请完成以下Java代码 | public void setRequestType (java.lang.String RequestType)
{
set_Value (COLUMNNAME_RequestType, RequestType);
}
/** Get Anfrageart.
@return Anfrageart */
@Override
public java.lang.String getRequestType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestType);
}
/** Set Ergebnis.
@param Result
Result of the action taken
*/
@Override
public void setResult (java.lang.String Result)
{
set_Value (COLUMNNAME_Result, Result);
}
/** Get Ergebnis.
@return Result of the action taken
*/
@Override
public java.lang.String getResult ()
{
return (java.lang.String)get_Value(COLUMNNAME_Result);
}
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{ | return (java.lang.String)get_Value(COLUMNNAME_Status);
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
@Override
public void setSummary (java.lang.String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Summary.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary ()
{
return (java.lang.String)get_Value(COLUMNNAME_Summary);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Request.java | 1 |
请完成以下Java代码 | default boolean processIt(final String docAction)
{
return Services.get(IDocumentBL.class).processIt(this, docAction);
}
/** @return true if success */
boolean unlockIt();
/** @return true if success */
boolean invalidateIt();
/** @return new status (In Progress or Invalid) */
String prepareIt();
/** @return true if success */
boolean approveIt();
/** @return true if success */
boolean rejectIt();
/** @return new status (Complete, In Progress, Invalid, Waiting ..) */
String completeIt();
/** @return true if success */
boolean voidIt();
/** @return true if success */
boolean closeIt();
default void unCloseIt()
{
throw new UnsupportedOperationException();
}
/** @return true if success */
boolean reverseCorrectIt();
/** @return true if success */
boolean reverseAccrualIt();
/** @return true if success */
boolean reActivateIt();
File createPDF();
/** @return Summary of Document */
String getSummary();
/** @return Document No */
String getDocumentNo();
/** @return Type and Document No */
String getDocumentInfo(); | int getDoc_User_ID();
int getC_Currency_ID();
BigDecimal getApprovalAmt();
int getAD_Client_ID();
int getAD_Org_ID();
boolean isActive();
void setDocStatus(String newStatus);
String getDocStatus();
String getDocAction();
LocalDate getDocumentDate();
Properties getCtx();
int get_ID();
int get_Table_ID();
/**
* @return true if saved
*/
boolean save();
String get_TrxName();
void set_TrxName(String trxName);
default TableRecordReference toTableRecordReference()
{
return TableRecordReference.of(get_Table_ID(), get_ID());
}
/**
* We use this constant in {@link org.adempiere.ad.wrapper.POJOWrapper}.
* Please keep it in sync with {@link #getDocumentModel()}.
*/
String METHOD_NAME_getDocumentModel = "getDocumentModel";
default Object getDocumentModel()
{
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\IDocument.java | 1 |
请在Spring Boot框架中完成以下Java代码 | ObservationHandlerGroup tracingObservationHandlerGroup(Tracer tracer) {
return ClassUtils.isPresent("io.micrometer.core.instrument.MeterRegistry", null)
? new TracingAndMeterObservationHandlerGroup(tracer)
: ObservationHandlerGroup.of(TracingObservationHandler.class);
}
@Bean
@ConditionalOnMissingBean
@Order(DEFAULT_TRACING_OBSERVATION_HANDLER_ORDER)
DefaultTracingObservationHandler defaultTracingObservationHandler(Tracer tracer) {
return new DefaultTracingObservationHandler(tracer);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(Propagator.class)
@Order(SENDER_TRACING_OBSERVATION_HANDLER_ORDER)
PropagatingSenderTracingObservationHandler<?> propagatingSenderTracingObservationHandler(Tracer tracer,
Propagator propagator) {
return new PropagatingSenderTracingObservationHandler<>(tracer, propagator);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(Propagator.class)
@Order(RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER)
PropagatingReceiverTracingObservationHandler<?> propagatingReceiverTracingObservationHandler(Tracer tracer,
Propagator propagator) {
return new PropagatingReceiverTracingObservationHandler<>(tracer, propagator);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Advice.class)
@ConditionalOnBooleanProperty("management.observations.annotations.enabled")
static class SpanAspectConfiguration {
@Bean
@ConditionalOnMissingBean(NewSpanParser.class) | DefaultNewSpanParser newSpanParser() {
return new DefaultNewSpanParser();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(ValueExpressionResolver.class)
SpanTagAnnotationHandler spanTagAnnotationHandler(BeanFactory beanFactory,
ValueExpressionResolver valueExpressionResolver) {
return new SpanTagAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver);
}
@Bean
@ConditionalOnMissingBean(MethodInvocationProcessor.class)
ImperativeMethodInvocationProcessor imperativeMethodInvocationProcessor(NewSpanParser newSpanParser,
Tracer tracer, ObjectProvider<SpanTagAnnotationHandler> spanTagAnnotationHandler) {
return new ImperativeMethodInvocationProcessor(newSpanParser, tracer,
spanTagAnnotationHandler.getIfAvailable());
}
@Bean
@ConditionalOnMissingBean
SpanAspect spanAspect(MethodInvocationProcessor methodInvocationProcessor) {
return new SpanAspect(methodInvocationProcessor);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\MicrometerTracingAutoConfiguration.java | 2 |
请完成以下Java代码 | public abstract class Lookup {
/**
* the array size
*/
final protected int s = 50000000;
/**
* Initialize the array: fill in the array with the same
* elements except for the last one.
*/
abstract public void prepare();
/**
* Free the array's reference.
*/
abstract public void clean();
/**
* Find the position of the element that is different from the others.
* By construction, it is the last array element.
*
* @return array's last element index
*/ | abstract public int findPosition();
/**
* Get the name of the class that extends this one. It is needed in order
* to set up the benchmark.
*
* @return
*/
abstract public String getSimpleClassName();
Collection<RunResult> run() throws RunnerException {
Options opt = new OptionsBuilder()
.include(getSimpleClassName())
.forks(1)
.build();
return new Runner(opt).run();
}
} | repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\Lookup.java | 1 |
请完成以下Java代码 | public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Report Line Set Name.
@param ReportLineSetName
Name of the Report Line Set
*/
public void setReportLineSetName (String ReportLineSetName)
{
set_Value (COLUMNNAME_ReportLineSetName, ReportLineSetName);
}
/** Get Report Line Set Name. | @return Name of the Report Line Set
*/
public String getReportLineSetName ()
{
return (String)get_Value(COLUMNNAME_ReportLineSetName);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_ReportLine.java | 1 |
请完成以下Java代码 | public class DefinitionsParser implements BpmnXMLConstants {
protected static final List<ExtensionAttribute> defaultAttributes = asList(
new ExtensionAttribute(TYPE_LANGUAGE_ATTRIBUTE),
new ExtensionAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE),
new ExtensionAttribute(TARGET_NAMESPACE_ATTRIBUTE)
);
@SuppressWarnings("unchecked")
public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception {
model.setTargetNamespace(xtr.getAttributeValue(null, TARGET_NAMESPACE_ATTRIBUTE));
for (int i = 0; i < xtr.getNamespaceCount(); i++) {
String prefix = xtr.getNamespacePrefix(i);
if (StringUtils.isNotEmpty(prefix)) {
model.addNamespace(prefix, xtr.getNamespaceURI(i));
}
}
for (int i = 0; i < xtr.getAttributeCount(); i++) { | ExtensionAttribute extensionAttribute = new ExtensionAttribute();
extensionAttribute.setName(xtr.getAttributeLocalName(i));
extensionAttribute.setValue(xtr.getAttributeValue(i));
if (StringUtils.isNotEmpty(xtr.getAttributeNamespace(i))) {
extensionAttribute.setNamespace(xtr.getAttributeNamespace(i));
}
if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) {
extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i));
}
if (!BpmnXMLUtil.isBlacklisted(extensionAttribute, defaultAttributes)) {
model.addDefinitionsAttribute(extensionAttribute);
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\parser\DefinitionsParser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JobQueryProperty implements QueryProperty {
private static final long serialVersionUID = 1L;
private static final Map<String, JobQueryProperty> properties = new HashMap<>();
public static final JobQueryProperty JOB_ID = new JobQueryProperty("ID_");
public static final JobQueryProperty PROCESS_INSTANCE_ID = new JobQueryProperty("RES.PROCESS_INSTANCE_ID_");
public static final JobQueryProperty EXECUTION_ID = new JobQueryProperty("RES.EXECUTION_ID_");
public static final JobQueryProperty DUEDATE = new JobQueryProperty("RES.DUEDATE_");
public static final JobQueryProperty CREATE_TIME = new JobQueryProperty("RES.CREATE_TIME_");
public static final JobQueryProperty RETRIES = new JobQueryProperty("RES.RETRIES_");
public static final JobQueryProperty TENANT_ID = new JobQueryProperty("RES.TENANT_ID_");
private String name; | public JobQueryProperty(String name) {
this.name = name;
properties.put(name, this);
}
@Override
public String getName() {
return name;
}
public static JobQueryProperty findByName(String propertyName) {
return properties.get(propertyName);
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\JobQueryProperty.java | 2 |
请完成以下Java代码 | public void save(@NonNull final Warehouse warehouse)
{
warehouseDAO.save(warehouse);
}
@NonNull
public Warehouse createWarehouse(@NonNull final CreateWarehouseRequest request)
{
return warehouseDAO.createWarehouse(request);
}
@Override
public Optional<LocationId> getLocationIdByLocatorRepoId(final int locatorRepoId)
{
final WarehouseId warehouseId = getIdByLocatorRepoId(locatorRepoId);
final I_M_Warehouse warehouse = getById(warehouseId);
return Optional.ofNullable(LocationId.ofRepoIdOrNull(warehouse.getC_Location_ID()));
}
@Override
public OrgId getOrgIdByLocatorRepoId(final int locatorId)
{
return warehouseDAO.retrieveOrgIdByLocatorId(locatorId);
}
@Override
@NonNull
public ImmutableSet<LocatorId> getLocatorIdsOfTheSamePickingGroup(@NonNull final WarehouseId warehouseId)
{
final Set<WarehouseId> pickFromWarehouseIds = warehouseDAO.getWarehouseIdsOfSamePickingGroup(warehouseId);
return warehouseDAO.getLocatorIdsByWarehouseIds(pickFromWarehouseIds);
}
@Override
@NonNull
public ImmutableSet<LocatorId> getLocatorIdsByRepoId(@NonNull final Collection<Integer> locatorIds)
{
return warehouseDAO.getLocatorIdsByRepoId(locatorIds);
}
@Override
public LocatorQRCode getLocatorQRCode(@NonNull final LocatorId locatorId)
{
final I_M_Locator locator = warehouseDAO.getLocatorById(locatorId);
return LocatorQRCode.ofLocator(locator);
} | @Override
@NonNull
public ExplainedOptional<LocatorQRCode> getLocatorQRCodeByValue(@NonNull String locatorValue)
{
final List<I_M_Locator> locators = getActiveLocatorsByValue(locatorValue);
if (locators.isEmpty())
{
return ExplainedOptional.emptyBecause(AdempiereException.MSG_NotFound);
}
else if (locators.size() > 1)
{
return ExplainedOptional.emptyBecause(DBMoreThanOneRecordsFoundException.MSG_QueryMoreThanOneRecordsFound);
}
else
{
final I_M_Locator locator = locators.get(0);
return ExplainedOptional.of(LocatorQRCode.ofLocator(locator));
}
}
@Override
public List<I_M_Locator> getActiveLocatorsByValue(final @NotNull String locatorValue)
{
return warehouseDAO.retrieveActiveLocatorsByValue(locatorValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseBL.java | 1 |
请完成以下Java代码 | public java.lang.String getPriorityRule ()
{
return (java.lang.String)get_Value(COLUMNNAME_PriorityRule);
}
/** 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 Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null) | {
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Summe Zeilen.
@param TotalLines
Total of all document lines
*/
@Override
public void setTotalLines (java.math.BigDecimal TotalLines)
{
set_Value (COLUMNNAME_TotalLines, TotalLines);
}
/** Get Summe Zeilen.
@return Total of all document lines
*/
@Override
public java.math.BigDecimal getTotalLines ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalLines);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Requisition.java | 1 |
请完成以下Java代码 | public String getF_HISTORYID() {
return F_HISTORYID;
}
public void setF_HISTORYID(String f_HISTORYID) {
F_HISTORYID = f_HISTORYID;
}
public String getF_STATUS() {
return F_STATUS;
}
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_VERSION() {
return F_VERSION;
}
public void setF_VERSION(String f_VERSION) {
F_VERSION = f_VERSION;
}
public String getF_ISSTD() {
return F_ISSTD;
}
public void setF_ISSTD(String f_ISSTD) {
F_ISSTD = f_ISSTD;
}
public Timestamp getF_EDITTIME() {
return F_EDITTIME;
}
public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME; | }
public String getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(String f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISENTERPRISES() {
return F_ISENTERPRISES;
}
public void setF_ISENTERPRISES(String f_ISENTERPRISES) {
F_ISENTERPRISES = f_ISENTERPRISES;
}
public String getF_ISCLEAR() {
return F_ISCLEAR;
}
public void setF_ISCLEAR(String f_ISCLEAR) {
F_ISCLEAR = f_ISCLEAR;
}
public String getF_PARENTID() {
return F_PARENTID;
}
public void setF_PARENTID(String f_PARENTID) {
F_PARENTID = f_PARENTID;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollItem.java | 1 |
请完成以下Java代码 | public final class ImmutableDocumentFilterDescriptorsProvider implements DocumentFilterDescriptorsProvider
{
public static ImmutableDocumentFilterDescriptorsProvider of(final List<DocumentFilterDescriptor> descriptors)
{
if (descriptors == null || descriptors.isEmpty())
{
return EMPTY;
}
return new ImmutableDocumentFilterDescriptorsProvider(descriptors);
}
public static ImmutableDocumentFilterDescriptorsProvider of(final DocumentFilterDescriptor... descriptors)
{
if (descriptors == null || descriptors.length == 0)
{
return EMPTY;
}
return new ImmutableDocumentFilterDescriptorsProvider(Arrays.asList(descriptors));
}
public static Builder builder()
{
return new Builder();
}
private static final ImmutableDocumentFilterDescriptorsProvider EMPTY = new ImmutableDocumentFilterDescriptorsProvider();
private final ImmutableMap<String, DocumentFilterDescriptor> descriptorsByFilterId;
private ImmutableDocumentFilterDescriptorsProvider(final List<DocumentFilterDescriptor> descriptors)
{
descriptorsByFilterId = Maps.uniqueIndex(descriptors, DocumentFilterDescriptor::getFilterId);
}
private ImmutableDocumentFilterDescriptorsProvider()
{
descriptorsByFilterId = ImmutableMap.of();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(descriptorsByFilterId.keySet())
.toString();
}
@Override
public Collection<DocumentFilterDescriptor> getAll()
{
return descriptorsByFilterId.values();
}
@Override
public DocumentFilterDescriptor getByFilterIdOrNull(final String filterId)
{
return descriptorsByFilterId.get(filterId);
}
//
// | //
//
//
public static class Builder
{
private final List<DocumentFilterDescriptor> descriptors = new ArrayList<>();
private Builder()
{
}
public ImmutableDocumentFilterDescriptorsProvider build()
{
if (descriptors.isEmpty())
{
return EMPTY;
}
return new ImmutableDocumentFilterDescriptorsProvider(descriptors);
}
public Builder addDescriptor(@NonNull final DocumentFilterDescriptor descriptor)
{
descriptors.add(descriptor);
return this;
}
public Builder addDescriptors(@NonNull final Collection<DocumentFilterDescriptor> descriptors)
{
if (descriptors.isEmpty())
{
return this;
}
this.descriptors.addAll(descriptors);
return this;
}
public Builder addDescriptors(@NonNull final DocumentFilterDescriptorsProvider provider)
{
addDescriptors(provider.getAll());
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\ImmutableDocumentFilterDescriptorsProvider.java | 1 |
请完成以下Java代码 | private void validateType(TbMsg msg) {
if (!msg.isTypeOf(TbMsgType.SEND_EMAIL)) {
String type = msg.getType();
log.warn("Not expected msg type [{}] for SendEmail Node", type);
throw new IllegalStateException("Not expected msg type " + type + " for SendEmail Node");
}
}
private JavaMailSenderImpl createMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(this.config.getSmtpHost());
mailSender.setPort(this.config.getSmtpPort());
mailSender.setUsername(this.config.getUsername());
mailSender.setPassword(this.config.getPassword());
mailSender.setJavaMailProperties(createJavaMailProperties());
return mailSender;
}
private Properties createJavaMailProperties() {
Properties javaMailProperties = new Properties();
String protocol = this.config.getSmtpProtocol();
javaMailProperties.put("mail.transport.protocol", protocol);
javaMailProperties.put(MAIL_PROP + protocol + ".host", this.config.getSmtpHost());
javaMailProperties.put(MAIL_PROP + protocol + ".port", this.config.getSmtpPort() + "");
javaMailProperties.put(MAIL_PROP + protocol + ".timeout", this.config.getTimeout() + "");
javaMailProperties.put(MAIL_PROP + protocol + ".auth", String.valueOf(StringUtils.isNotEmpty(this.config.getUsername()))); | javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", Boolean.valueOf(this.config.isEnableTls()).toString());
if (this.config.isEnableTls() && StringUtils.isNoneEmpty(this.config.getTlsVersion())) {
javaMailProperties.put(MAIL_PROP + protocol + ".ssl.protocols", this.config.getTlsVersion());
}
if (this.config.isEnableProxy()) {
javaMailProperties.put(MAIL_PROP + protocol + ".proxy.host", config.getProxyHost());
javaMailProperties.put(MAIL_PROP + protocol + ".proxy.port", config.getProxyPort());
if (StringUtils.isNoneEmpty(config.getProxyUser())) {
javaMailProperties.put(MAIL_PROP + protocol + ".proxy.user", config.getProxyUser());
}
if (StringUtils.isNoneEmpty(config.getProxyPassword())) {
javaMailProperties.put(MAIL_PROP + protocol + ".proxy.password", config.getProxyPassword());
}
}
return javaMailProperties;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mail\TbSendEmailNode.java | 1 |
请完成以下Java代码 | public class Metrics {
public static final String ACTIVTY_INSTANCE_START = "activity-instance-start";
public static final String ACTIVTY_INSTANCE_END = "activity-instance-end";
public static final String FLOW_NODE_INSTANCES = "flow-node-instances";
/**
* Number of times job acquisition is performed
*/
public static final String JOB_ACQUISITION_ATTEMPT = "job-acquisition-attempt";
/**
* Number of jobs successfully acquired (i.e. selected + locked)
*/
public static final String JOB_ACQUIRED_SUCCESS = "job-acquired-success";
/**
* Number of jobs attempted to acquire but with failure (i.e. selected + lock failed)
*/
public static final String JOB_ACQUIRED_FAILURE = "job-acquired-failure";
/**
* Number of jobs that were submitted for execution but were rejected due to
* resource shortage. In the default job executor, this is the case when
* the execution queue is full.
*/
public static final String JOB_EXECUTION_REJECTED = "job-execution-rejected";
public static final String JOB_SUCCESSFUL = "job-successful";
public static final String JOB_FAILED = "job-failed";
/**
* Number of jobs that are immediately locked and executed because they are exclusive
* and created in the context of job execution
*/
public static final String JOB_LOCKED_EXCLUSIVE = "job-locked-exclusive"; | /**
* Number of executed Root Process Instance executions.
*/
public static final String ROOT_PROCESS_INSTANCE_START = "root-process-instance-start";
public static final String PROCESS_INSTANCES = "process-instances";
/**
* Number of executed decision elements in the DMN engine.
*/
public static final String EXECUTED_DECISION_ELEMENTS = "executed-decision-elements";
public static final String EXECUTED_DECISION_INSTANCES = "executed-decision-instances";
public static final String DECISION_INSTANCES = "decision-instances";
/**
* Number of instances removed by history cleanup.
*/
public static final String HISTORY_CLEANUP_REMOVED_PROCESS_INSTANCES = "history-cleanup-removed-process-instances";
public static final String HISTORY_CLEANUP_REMOVED_CASE_INSTANCES = "history-cleanup-removed-case-instances";
public static final String HISTORY_CLEANUP_REMOVED_DECISION_INSTANCES = "history-cleanup-removed-decision-instances";
public static final String HISTORY_CLEANUP_REMOVED_BATCH_OPERATIONS = "history-cleanup-removed-batch-operations";
public static final String HISTORY_CLEANUP_REMOVED_TASK_METRICS = "history-cleanup-removed-task-metrics";
/**
* Number of unique task workers
*/
public static final String UNIQUE_TASK_WORKERS = "unique-task-workers";
public static final String TASK_USERS = "task-users";
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\management\Metrics.java | 1 |
请完成以下Java代码 | public void removeAttribute(String attributeName) {
this.sessionAttrs.remove(attributeName);
}
/**
* Sets the time that this {@link Session} was created. The default is when the
* {@link Session} was instantiated.
* @param creationTime the time that this {@link Session} was created.
*/
public void setCreationTime(Instant creationTime) {
this.creationTime = creationTime;
}
/**
* Sets the identifier for this {@link Session}. The id should be a secure random
* generated value to prevent malicious users from guessing this value. The default is
* a secure random generated identifier.
* @param id the identifier for this session.
*/
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Session && this.id.equals(((Session) obj).getId());
} | @Override
public int hashCode() {
return this.id.hashCode();
}
private static String generateId() {
return UUID.randomUUID().toString();
}
/**
* Sets the {@link SessionIdGenerator} to use when generating a new session id.
* @param sessionIdGenerator the {@link SessionIdGenerator} to use.
* @since 3.2
*/
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
private static final long serialVersionUID = 7160779239673823561L;
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSession.java | 1 |
请完成以下Java代码 | public StockQtyAndUOMQty computeQtysWithIssuesEffective(
@Nullable final Percent qualityDiscountOverride,
@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn)
{
if (qualityDiscountOverride == null)
{
return getQtysWithIssues(invoicableQtyBasedOn);
}
final Quantity qtyTotal = getQtysTotal(invoicableQtyBasedOn).getUOMQtyNotNull();
final Quantity qtyTotalInStockUom = getQtysTotal(invoicableQtyBasedOn).getStockQty();
final BigDecimal qtyWithIssuesEffective = qualityDiscountOverride.computePercentageOf(
qtyTotal.toBigDecimal(),
qtyTotal.getUOM().getStdPrecision());
final BigDecimal qtyWithIssuesInStockUomEffective = qualityDiscountOverride.computePercentageOf(
qtyTotalInStockUom.toBigDecimal(),
qtyTotalInStockUom.getUOM().getStdPrecision());
return StockQtyAndUOMQtys.create( | qtyWithIssuesInStockUomEffective, productId,
qtyWithIssuesEffective, qtyTotal.getUomId());
}
public StockQtyAndUOMQty computeInvoicableQtyDelivered(
@Nullable final Percent qualityDiscountOverride,
@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn)
{
final StockQtyAndUOMQty qtysWithIssuesEffective = computeQtysWithIssuesEffective(qualityDiscountOverride, invoicableQtyBasedOn);
return getQtysTotal(invoicableQtyBasedOn).subtract(qtysWithIssuesEffective);
}
public Percent computeQualityDiscount(@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn)
{
return Percent.of(
getQtysWithIssues(invoicableQtyBasedOn).getUOMQtyNotNull().toBigDecimal(),
getQtysTotal(invoicableQtyBasedOn).getUOMQtyNotNull().toBigDecimal());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\ReceiptData.java | 1 |
请完成以下Java代码 | public UIComponent getUIComponent(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts)
{
final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess);
return UIComponent.builderFrom(COMPONENT_TYPE, wfActivity)
.properties(Params.builder()
.valueObj("scaleDevice", getCurrentScaleDevice(job, jsonOpts))
.valueObj("lines", getLines(job, wfActivity.getId(), jsonOpts))
.valueObj("qtyRejectedReasons", getJsonRejectReasonsList(jsonOpts))
.build())
.build();
}
@Nullable
private JsonScaleDevice getCurrentScaleDevice(final ManufacturingJob job, final @NonNull JsonOpts jsonOpts)
{
return manufacturingJobService.getCurrentScaleDevice(job)
.map(scaleDevice -> JsonScaleDevice.of(scaleDevice, jsonOpts.getAdLanguage()))
.orElse(null);
}
private ImmutableList<JsonRawMaterialsIssueLine> getLines(final ManufacturingJob job, final @NonNull WFActivityId wfActivityId, final @NonNull JsonOpts jsonOpts)
{
return job.getActivityById(wfActivityId)
.getRawMaterialsIssueAssumingNotNull()
.getLines().stream()
.map(line -> toJson(line, jsonOpts))
.collect(ImmutableList.toImmutableList());
}
private JsonRawMaterialsIssueLine toJson(final @NonNull RawMaterialsIssueLine line, final @NonNull JsonOpts jsonOpts)
{
return JsonRawMaterialsIssueLine.builderFrom(line, jsonOpts)
.hazardSymbols(getJsonHazardSymbols(line.getProductId(), jsonOpts.getAdLanguage()))
.allergens(getJsonAllergens(line.getProductId(), jsonOpts.getAdLanguage()))
.build();
}
private ImmutableList<JsonHazardSymbol> getJsonHazardSymbols(final @NonNull ProductId productId, final String adLanguage) | {
return productHazardSymbolService.getHazardSymbolsByProductId(productId)
.stream()
.map(hazardSymbol -> JsonHazardSymbol.of(hazardSymbol, adLanguage))
.collect(ImmutableList.toImmutableList());
}
private ImmutableList<JsonAllergen> getJsonAllergens(final @NonNull ProductId productId, final String adLanguage)
{
return productAllergensService.getAllergensByProductId(productId)
.stream()
.map(allergen -> JsonAllergen.of(allergen, adLanguage))
.collect(ImmutableList.toImmutableList());
}
private JsonRejectReasonsList getJsonRejectReasonsList(final @NonNull JsonOpts jsonOpts)
{
return JsonRejectReasonsList.of(adReferenceService.getRefListById(QtyRejectedReasonCode.REFERENCE_ID), jsonOpts);
}
@Override
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity)
{
return wfActivity.getStatus();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\issue\RawMaterialsIssueActivityHandler.java | 1 |
请完成以下Java代码 | public void setQty (final BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInUOM (final @Nullable BigDecimal QtyInUOM)
{
set_Value (COLUMNNAME_QtyInUOM, QtyInUOM);
}
@Override
public BigDecimal getQtyInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* Type AD_Reference_ID=541716 | * Reference name: M_MatchInv_Type
*/
public static final int TYPE_AD_Reference_ID=541716;
/** Material = M */
public static final String TYPE_Material = "M";
/** Cost = C */
public static final String TYPE_Cost = "C";
@Override
public void setType (final java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchInv.java | 1 |
请完成以下Java代码 | public ModificationRestService getModificationRestService(@PathParam("name") String engineName) {
return super.getModificationRestService(engineName);
}
@Override
@Path("/{name}" + BatchRestService.PATH)
public BatchRestService getBatchRestService(@PathParam("name") String engineName) {
return super.getBatchRestService(engineName);
}
@Override
@Path("/{name}" + TenantRestService.PATH)
public TenantRestService getTenantRestService(@PathParam("name") String engineName) {
return super.getTenantRestService(engineName);
}
@Override
@Path("/{name}" + SignalRestService.PATH)
public SignalRestService getSignalRestService(@PathParam("name") String engineName) {
return super.getSignalRestService(engineName);
}
@Override
@Path("/{name}" + ConditionRestService.PATH)
public ConditionRestService getConditionRestService(@PathParam("name") String engineName) {
return super.getConditionRestService(engineName);
}
@Path("/{name}" + OptimizeRestService.PATH)
public OptimizeRestService getOptimizeRestService(@PathParam("name") String engineName) {
return super.getOptimizeRestService(engineName);
}
@Path("/{name}" + VersionRestService.PATH)
public VersionRestService getVersionRestService(@PathParam("name") String engineName) {
return super.getVersionRestService(engineName);
}
@Path("/{name}" + SchemaLogRestService.PATH)
public SchemaLogRestService getSchemaLogRestService(@PathParam("name") String engineName) {
return super.getSchemaLogRestService(engineName);
}
@Override
@Path("/{name}" + EventSubscriptionRestService.PATH) | public EventSubscriptionRestService getEventSubscriptionRestService(@PathParam("name") String engineName) {
return super.getEventSubscriptionRestService(engineName);
}
@Override
@Path("/{name}" + TelemetryRestService.PATH)
public TelemetryRestService getTelemetryRestService(@PathParam("name") String engineName) {
return super.getTelemetryRestService(engineName);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<ProcessEngineDto> getProcessEngineNames() {
ProcessEngineProvider provider = getProcessEngineProvider();
Set<String> engineNames = provider.getProcessEngineNames();
List<ProcessEngineDto> results = new ArrayList<ProcessEngineDto>();
for (String engineName : engineNames) {
ProcessEngineDto dto = new ProcessEngineDto();
dto.setName(engineName);
results.add(dto);
}
return results;
}
@Override
protected URI getRelativeEngineUri(String engineName) {
return UriBuilder.fromResource(NamedProcessEngineRestServiceImpl.class).path("{name}").build(engineName);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\NamedProcessEngineRestServiceImpl.java | 1 |
请完成以下Java代码 | public I_M_Material_Tracking getM_MaterialTracking()
{
return materialTracking;
}
private int getM_MaterialTracking_ID()
{
final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID();
return materialTrackingId > 0 ? materialTrackingId : -1;
}
protected void add(@NonNull final HUPackingMaterialDocumentLineCandidate candidateToAdd)
{
if (this == candidateToAdd)
{
throw new IllegalArgumentException("Cannot add to it self: " + candidateToAdd);
}
if (!Objects.equals(getProductId(), candidateToAdd.getProductId())
|| getC_UOM_ID() != candidateToAdd.getC_UOM_ID()
|| getM_Locator_ID() != candidateToAdd.getM_Locator_ID()
|| getM_MaterialTracking_ID() != candidateToAdd.getM_MaterialTracking_ID())
{
throw new HUException("Candidates are not matching."
+ "\nthis: " + this
+ "\ncandidate to add: " + candidateToAdd);
}
qty = qty.add(candidateToAdd.qty);
// add sources; might be different | addSources(candidateToAdd.getSources());
}
public void addSourceIfNotNull(final IHUPackingMaterialCollectorSource huPackingMaterialCollectorSource)
{
if (huPackingMaterialCollectorSource != null)
{
sources.add(huPackingMaterialCollectorSource);
}
}
private void addSources(final Set<IHUPackingMaterialCollectorSource> huPackingMaterialCollectorSources)
{
if (!huPackingMaterialCollectorSources.isEmpty())
{
sources.addAll(huPackingMaterialCollectorSources);
}
}
public Set<IHUPackingMaterialCollectorSource> getSources()
{
return ImmutableSet.copyOf(sources);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\spi\impl\HUPackingMaterialDocumentLineCandidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HistoricEntityLinkEntity create() {
HistoricEntityLinkEntity entityLinkEntity = super.create();
entityLinkEntity.setCreateTime(getClock().getCurrentTime());
return entityLinkEntity;
}
@Override
public List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType) {
return dataManager.findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(scopeId, scopeType, linkType);
}
@Override
public List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType, String linkType) {
return dataManager.findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(scopeIds, scopeType, linkType);
}
@Override
public InternalEntityLinkQuery<HistoricEntityLinkEntity> createInternalHistoricEntityLinkQuery() {
return new InternalEntityLinkQueryImpl<>(dataManager::findHistoricEntityLinksByQuery, dataManager::findHistoricEntityLinkByQuery);
}
@Override
public void deleteHistoricEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
dataManager.deleteHistoricEntityLinksByScopeIdAndType(scopeId, scopeType);
}
@Override
public void deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) {
dataManager.deleteHistoricEntityLinksByScopeDefinitionIdAndType(scopeDefinitionId, scopeType);
} | @Override
public void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds) {
dataManager.bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(scopeType, scopeIds);
}
@Override
public void deleteHistoricEntityLinksForNonExistingProcessInstances() {
dataManager.deleteHistoricEntityLinksForNonExistingProcessInstances();
}
@Override
public void deleteHistoricEntityLinksForNonExistingCaseInstances() {
dataManager.deleteHistoricEntityLinksForNonExistingCaseInstances();
}
} | repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\HistoricEntityLinkEntityManagerImpl.java | 2 |
请完成以下Java代码 | protected String doIt()
{
final I_C_BankStatement bankStatement = getSelectedBankStatement();
final I_C_BankStatementLine bankStatementLine = getSingleSelectedBankStatementLine();
bankStatementLine.setC_BPartner_ID(bpartnerId.getRepoId());
if (paymentId != null)
{
bankStatementPaymentBL.linkSinglePayment(bankStatement, bankStatementLine, paymentId);
}
else
{
final Set<PaymentId> eligiblePaymentIds = bankStatementPaymentBL.findEligiblePaymentIds(
bankStatementLine,
bpartnerId,
ImmutableSet.of(), // excludePaymentIds
2 // limit
); | if (eligiblePaymentIds.isEmpty())
{
bankStatementPaymentBL.createSinglePaymentAndLink(bankStatement, bankStatementLine);
}
else if (eligiblePaymentIds.size() == 1)
{
PaymentId eligiblePaymentId = eligiblePaymentIds.iterator().next();
bankStatementPaymentBL.linkSinglePayment(bankStatement, bankStatementLine, eligiblePaymentId);
}
else
{
throw new FillMandatoryException(PARAM_C_Payment_ID);
}
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\banking\process\C_BankStatement_ReconcileWithSinglePayment.java | 1 |
请完成以下Java代码 | public int getAsyncJobLockTimeInMillis() {
return asyncJobLockTimeInMillis;
}
public void setAsyncJobLockTimeInMillis(int asyncJobLockTimeInMillis) {
this.asyncJobLockTimeInMillis = asyncJobLockTimeInMillis;
}
public int getRetryWaitTimeInMillis() {
return retryWaitTimeInMillis;
}
public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) {
this.retryWaitTimeInMillis = retryWaitTimeInMillis;
}
public int getResetExpiredJobsInterval() {
return resetExpiredJobsInterval;
}
public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) { | this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public int getNumberOfRetries() {
return numberOfRetries;
}
public void setNumberOfRetries(int numberOfRetries) {
this.numberOfRetries = numberOfRetries;
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AsyncExecutorProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StartApplication {
private static final Logger log = LoggerFactory.getLogger(StartApplication.class);
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
@Autowired
BookRepository bookRepository;
@Bean
public CommandLineRunner startup() {
return args -> {
Book b1 = new Book("Book A",
BigDecimal.valueOf(9.99),
LocalDate.of(2023, 8, 31));
Book b2 = new Book("Book B", | BigDecimal.valueOf(19.99),
LocalDate.of(2023, 7, 31));
Book b3 = new Book("Book C",
BigDecimal.valueOf(29.99),
LocalDate.of(2023, 6, 10));
Book b4 = new Book("Book D",
BigDecimal.valueOf(39.99),
LocalDate.of(2023, 5, 5));
Book b5 = new Book("Book E",
BigDecimal.valueOf(49.99),
LocalDate.of(2023, 4, 1));
Book b6 = new Book("Book F",
BigDecimal.valueOf(59.99),
LocalDate.of(2023, 3, 1));
bookRepository.saveAll(List.of(b1, b2, b3, b4, b5, b6));
};
}
} | repos\spring-boot-master\spring-data-jpa-paging-sorting\src\main\java\com\mkyong\StartApplication.java | 2 |
请完成以下Java代码 | private static boolean hasLoopInTree (final I_M_Product_Category productCategory)
{
final int productCategoryId = productCategory.getM_Product_Category_ID();
final int newParentCategoryId = productCategory.getM_Product_Category_Parent_ID();
// get values
ResultSet rs = null;
PreparedStatement pstmt = null;
final String sql = " SELECT M_Product_Category_ID, M_Product_Category_Parent_ID FROM M_Product_Category";
final Vector<SimpleTreeNode> categories = new Vector<>(100);
try {
pstmt = DB.prepareStatement(sql, null);
rs = pstmt.executeQuery();
while (rs.next()) {
if (rs.getInt(1) == productCategoryId)
categories.add(new SimpleTreeNode(rs.getInt(1), newParentCategoryId));
categories.add(new SimpleTreeNode(rs.getInt(1), rs.getInt(2)));
}
if (hasLoop(newParentCategoryId, categories, productCategoryId))
return true;
} catch (final SQLException e) {
log.error(sql, e);
return true;
}
finally
{
DB.close(rs, pstmt);
}
return false;
} // hasLoopInTree
/**
* Recursive search for parent nodes - climbs the to the root.
* If there is a circle there is no root but it comes back to the start node.
*/
private static boolean hasLoop(final int parentCategoryId, final Vector<SimpleTreeNode> categories, final int loopIndicatorId) {
final Iterator<SimpleTreeNode> iter = categories.iterator();
boolean ret = false;
while (iter.hasNext()) {
final SimpleTreeNode node = iter.next();
if(node.getNodeId()==parentCategoryId){
if (node.getParentId()==0) {
//root node, all fine
return false;
}
if(node.getNodeId()==loopIndicatorId){
//loop found | return true;
}
ret = hasLoop(node.getParentId(), categories, loopIndicatorId);
}
}
return ret;
} //hasLoop
/**
* Simple class for tree nodes.
* @author Karsten Thiemann, kthiemann@adempiere.org
*
*/
private static class SimpleTreeNode {
/** id of the node */
private final int nodeId;
/** id of the nodes parent */
private final int parentId;
public SimpleTreeNode(final int nodeId, final int parentId) {
this.nodeId = nodeId;
this.parentId = parentId;
}
public int getNodeId() {
return nodeId;
}
public int getParentId() {
return parentId;
}
}
} // MProductCategory | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MProductCategory.java | 1 |
请完成以下Java代码 | public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public long getRetryTimeout() {
return retryTimeout;
}
public void setRetryTimeout(long retryTimeout) {
this.retryTimeout = retryTimeout;
}
public int getRetries() {
return retries;
}
public void setRetries(int retries) {
this.retries = retries;
}
public String getErrorDetails() {
return errorDetails;
}
public void setErrorDetails(String errorDetails) {
this.errorDetails = errorDetails;
} | public Map<String, VariableValueDto> getVariables() {
return variables;
}
public void setVariables(Map<String, VariableValueDto> variables) {
this.variables = variables;
}
public Map<String, VariableValueDto> getLocalVariables() {
return localVariables;
}
public void setLocalVariables(Map<String, VariableValueDto> localVariables) {
this.localVariables = localVariables;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\ExternalTaskFailureDto.java | 1 |
请完成以下Java代码 | public void addBottomCategory(BottomCategory bottomCategory) {
bottomCategories.add(bottomCategory);
bottomCategory.setMiddleCategory(this);
}
public void removeBottomCategory(BottomCategory bottomCategory) {
bottomCategory.setMiddleCategory(null);
bottomCategories.remove(bottomCategory);
}
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 List<BottomCategory> getBottomCategories() {
return bottomCategories;
}
public void setBottomCategories(List<BottomCategory> bottomCategories) { | this.bottomCategories = bottomCategories;
}
public TopCategory getTopCategory() {
return topCategory;
}
public void setTopCategory(TopCategory topCategory) {
this.topCategory = topCategory;
}
@Override
public int hashCode() {
return 2018;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MiddleCategory)) {
return false;
}
return id != null && id.equals(((MiddleCategory) obj).id);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSqlResultSetMapping\src\main\java\com\app\entity\MiddleCategory.java | 1 |
请完成以下Java代码 | public void setC_DunningRun_ID (int C_DunningRun_ID)
{
if (C_DunningRun_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DunningRun_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DunningRun_ID, Integer.valueOf(C_DunningRun_ID));
}
/** Get Dunning Run.
@return Dunning Run
*/
public int getC_DunningRun_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningRun_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getC_DunningRun_ID()));
}
/** Set Note.
@param Note
Optional additional user defined information
*/
public void setNote (String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Note.
@return Optional additional user defined information
*/
public String getNote ()
{
return (String)get_Value(COLUMNNAME_Note);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{ | if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_C_DunningRunEntry.java | 1 |
请完成以下Spring Boot application配置 | # Custom properties to ease configuration overrides
# on command-line or IDE launch configurations
scheme: http
hostname: localhost
reverse-proxy-port: 7080
angular-port: 4201
angular-prefix: /angular-ui
# Update scheme if you enable SSL in angular.json
angular-uri: http://${hostname}:${angular-port}${angular-prefix}
vue-port: 4202
vue-prefix: /vue-ui
# Update scheme if you enable SSL in vite.config.ts
vue-uri: http://${hostname}:${vue-port}${vue-prefix}
react-port: 4203
react-prefix: /react-ui
react-uri: http://${hostname}:${react-port}${react-prefix}
authorization-server-port: 8080
authorization-server-prefix: /auth
authorization-server-uri: ${scheme}://${hostname}:${authorization-server-port}${authorization-server-prefix}
bff-port: 7081
bff-prefix: /bff
bff-uri: ${scheme}://${hostname}:${bff-port}
server:
port: ${reverse-proxy-port}
ssl:
enabled: false
spring:
cloud:
gateway:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
routes:
# SPAs assets
- id: angular-ui
uri: ${angular-uri}
predicates:
- Path=${angular-prefix}/**
- id: vue-ui
uri: ${vue-uri}
predicates:
- Path=${vue-prefix}/**
- id: react-ui
uri: ${react-uri}
predicates:
- Path=${react-prefix}/**
# Authorization-server
- id: authorization-server
uri: ${authorization-server-uri}
predicates:
- Path=${authorization-server-prefix}/**
# Proxy BFF
- id: bff
uri: ${bff-uri}
predicates:
- Path=${bff-prefix}/**
filters:
- StripPrefix=1
management:
endpoint:
health:
probes:
enabled: true
endpoints:
web:
exposure:
include: '*'
health:
livenessstate:
enabled: true
readinessstate:
enabled: true
logging:
level:
root: INFO
org:
springframework:
boot: INFO
web: INFO
---
spring:
config:
activate:
on-profile: ssl
server:
ssl:
enabled: true
scheme: https
authorization-server-port: 8443
---
spring:
config:
activate:
on-profile: cognito
cloud:
gateway:
routes:
# SPAs assets
- id: angular-ui
uri: ${angular-uri}
predicates:
- Path=${angular-prefi | x}/**
- id: vue-ui
uri: ${vue-uri}
predicates:
- Path=${vue-prefix}/**
- id: react-ui
uri: ${react-uri}
predicates:
- Path=${react-prefix}/**
# not routing to authorization server here
# Proxy BFF
- id: bff
uri: ${bff-uri}
predicates:
- Path=${bff-prefix}/**
filters:
- StripPrefix=1
---
spring:
config:
activate:
on-profile: auth0
cloud:
gateway:
routes:
# SPAs assets
- id: angular-ui
uri: ${angular-uri}
predicates:
- Path=${angular-prefix}/**
- id: vue-ui
uri: ${vue-uri}
predicates:
- Path=${vue-prefix}/**
- id: react-ui
uri: ${react-uri}
predicates:
- Path=${react-prefix}/**
# not routing to authorization server here
# Proxy BFF
- id: bff
uri: ${bff-uri}
predicates:
- Path=${bff-prefix}/**
filters:
- StripPrefix=1 | repos\tutorials-master\spring-security-modules\spring-security-oauth2-bff\backend\reverse-proxy\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public class OrderConsumer {
@Autowired
ProductService productService;
@Autowired
OrderProducer orderProducer;
@KafkaListener(topics = "orders", groupId = "inventory")
public void consume(Order order) throws IOException {
log.info("Order received to process: {}", order);
if (OrderStatus.RESERVE_INVENTORY.equals(order.getOrderStatus())) {
productService.handleOrder(order)
.doOnSuccess(o -> {
log.info("Order processed succesfully.");
orderProducer.sendMessage(order.setOrderStatus(OrderStatus.INVENTORY_SUCCESS));
})
.doOnError(e -> {
if (log.isDebugEnabled())
log.error("Order failed to process: " + e); | orderProducer.sendMessage(order.setOrderStatus(OrderStatus.INVENTORY_FAILURE)
.setResponseMessage(e.getMessage()));
})
.subscribe();
} else if (OrderStatus.REVERT_INVENTORY.equals(order.getOrderStatus())) {
productService.revertOrder(order)
.doOnSuccess(o -> {
log.info("Order reverted succesfully.");
orderProducer.sendMessage(order.setOrderStatus(OrderStatus.INVENTORY_REVERT_SUCCESS));
})
.doOnError(e -> {
if (log.isDebugEnabled())
log.error("Order failed to revert: " + e);
orderProducer.sendMessage(order.setOrderStatus(OrderStatus.INVENTORY_REVERT_FAILURE)
.setResponseMessage(e.getMessage()));
})
.subscribe();
}
}
} | repos\tutorials-master\reactive-systems\inventory-service\src\main\java\com\baeldung\async\consumer\OrderConsumer.java | 1 |
请完成以下Java代码 | public abstract class AbstractApiKeyInfoEntity<T extends ApiKeyInfo> extends BaseSqlEntity<T> implements BaseEntity<T> {
@Column(name = API_KEY_TENANT_ID_COLUMN_NAME)
private UUID tenantId;
@Column(name = API_KEY_USER_ID_COLUMN_NAME)
private UUID userId;
@Column(name = API_KEY_EXPIRATION_TIME_COLUMN_NAME)
private long expirationTime;
@Column(name = API_KEY_ENABLED_COLUMN_NAME)
private boolean enabled;
@Column(name = API_KEY_DESCRIPTION_COLUMN_NAME)
private String description;
public AbstractApiKeyInfoEntity() {
super();
}
public AbstractApiKeyInfoEntity(ApiKeyInfo apiKeyInfo) {
super(apiKeyInfo);
this.tenantId = apiKeyInfo.getTenantId().getId();
this.userId = apiKeyInfo.getUserId().getId();
this.expirationTime = apiKeyInfo.getExpirationTime();
this.description = apiKeyInfo.getDescription(); | this.enabled = apiKeyInfo.isEnabled();
}
protected ApiKeyInfo toApiKeyInfo() {
ApiKeyInfo apiKeyInfo = new ApiKeyInfo(new ApiKeyId(getUuid()));
apiKeyInfo.setCreatedTime(createdTime);
apiKeyInfo.setTenantId(TenantId.fromUUID(tenantId));
apiKeyInfo.setUserId(new UserId(userId));
apiKeyInfo.setEnabled(enabled);
apiKeyInfo.setExpirationTime(expirationTime);
apiKeyInfo.setDescription(description);
return apiKeyInfo;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\AbstractApiKeyInfoEntity.java | 1 |
请完成以下Java代码 | public UserNotificationsList getNotificationsAsList(@NonNull final QueryLimit limit)
{
final List<UserNotification> notifications = notificationsRepo.getByUserId(userId, limit);
final boolean fullyLoaded = limit.isNoLimit() || notifications.size() <= limit.toInt();
final int totalCount;
final int unreadCount;
if (fullyLoaded)
{
totalCount = notifications.size();
unreadCount = (int)notifications.stream().filter(UserNotification::isNotRead).count();
}
else
{
totalCount = notificationsRepo.getTotalCountByUserId(userId);
unreadCount = notificationsRepo.getUnreadCountByUserId(userId);
}
return UserNotificationsList.of(notifications, totalCount, unreadCount);
}
public void addActiveSessionId(final WebuiSessionId sessionId)
{
Check.assumeNotNull(sessionId, "Parameter sessionId is not null");
activeSessions.add(sessionId);
logger.debug("Added sessionId '{}' to {}", sessionId, this);
}
public void removeActiveSessionId(final WebuiSessionId sessionId)
{
activeSessions.remove(sessionId);
logger.debug("Removed sessionId '{}' to {}", sessionId, this);
}
public boolean hasActiveSessions()
{
return !activeSessions.isEmpty();
}
/* package */void addNotification(@NonNull final UserNotification notification)
{
final UserId adUserId = getUserId();
Check.assume(notification.getRecipientUserId() == adUserId.getRepoId(), "notification's recipient user ID shall be {}: {}", adUserId, notification);
final JSONNotification jsonNotification = JSONNotification.of(notification, jsonOptions);
fireEventOnWebsocket(JSONNotificationEvent.eventNew(jsonNotification, getUnreadCount())); | }
public void markAsRead(final String notificationId)
{
notificationsRepo.markAsReadById(Integer.parseInt(notificationId));
fireEventOnWebsocket(JSONNotificationEvent.eventRead(notificationId, getUnreadCount()));
}
public void markAllAsRead()
{
logger.trace("Marking all notifications as read (if any) for {}...", this);
notificationsRepo.markAllAsReadByUserId(getUserId());
fireEventOnWebsocket(JSONNotificationEvent.eventReadAll());
}
public int getUnreadCount()
{
return notificationsRepo.getUnreadCountByUserId(getUserId());
}
public void setLanguage(@NonNull final String adLanguage)
{
this.jsonOptions = jsonOptions.withAdLanguage(adLanguage);
}
public void delete(final String notificationId)
{
notificationsRepo.deleteById(Integer.parseInt(notificationId));
fireEventOnWebsocket(JSONNotificationEvent.eventDeleted(notificationId, getUnreadCount()));
}
public void deleteAll()
{
notificationsRepo.deleteAllByUserId(getUserId());
fireEventOnWebsocket(JSONNotificationEvent.eventDeletedAll());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\UserNotificationsQueue.java | 1 |
请完成以下Java代码 | default boolean isExploded() {
return getRootDirectory() != null;
}
/**
* Returns the root directory of this archive or {@code null} if the archive is not
* backed by a directory.
* @return the root directory
*/
default File getRootDirectory() {
return null;
}
/**
* Closes the {@code Archive}, releasing any open resources.
* @throws Exception if an error occurs during close processing
*/
@Override
default void close() throws Exception {
}
/**
* Factory method to create an appropriate {@link Archive} from the given
* {@link Class} target.
* @param target a target class that will be used to find the archive code source
* @return an new {@link Archive} instance
* @throws Exception if the archive cannot be created
*/
static Archive create(Class<?> target) throws Exception {
return create(target.getProtectionDomain());
}
static Archive create(ProtectionDomain protectionDomain) throws Exception {
CodeSource codeSource = protectionDomain.getCodeSource();
URI location = (codeSource != null) ? codeSource.getLocation().toURI() : null;
if (location == null) {
throw new IllegalStateException("Unable to determine code source archive");
}
return create(Path.of(location).toFile());
}
/**
* Factory method to create an {@link Archive} from the given {@link File} target.
* @param target a target {@link File} used to create the archive. May be a directory
* or a jar file.
* @return a new {@link Archive} instance.
* @throws Exception if the archive cannot be created
*/ | static Archive create(File target) throws Exception {
if (!target.exists()) {
throw new IllegalStateException("Unable to determine code source archive from " + target);
}
return (target.isDirectory() ? new ExplodedArchive(target) : new JarFileArchive(target));
}
/**
* Represents a single entry in the archive.
*/
interface Entry {
/**
* Returns the name of the entry.
* @return the name of the entry
*/
String name();
/**
* Returns {@code true} if the entry represents a directory.
* @return if the entry is a directory
*/
boolean isDirectory();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\Archive.java | 1 |
请完成以下Java代码 | public static int getCurrentHour() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
return cal.get(Calendar.HOUR_OF_DAY); // 获取当前小时
}
/***
* 查询当前分钟
*
* @return
*/
public static int getCurrentMinute() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
return cal.get(Calendar.MINUTE); // 获取当前分钟
}
/***
* 获取几天前的日期格式
*
* @param dayNum
* @return
*/
public static String getDateByDayNum(int dayNum) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); | Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_MONTH, -dayNum);
String result = sdf.format(cal.getTime());
return result;
}
/**
* 计算 day 天后的时间
*
* @param date
* @param day
* @return
*/
public static Date addDay(Date date, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
}
} | repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\utils\DateUtil.java | 1 |
请完成以下Java代码 | protected Map<String, Object> resolveBeanMetadata(final Object bean) {
final Map<String, Object> beanMetadata = new LinkedHashMap<>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod != null && isSimpleType(propertyDescriptor.getPropertyType())) {
String name = Introspector.decapitalize(propertyDescriptor.getName());
Object value = readMethod.invoke(bean);
beanMetadata.put(name, value);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} | return beanMetadata;
}
protected Map<String, ServiceBean> getServiceBeansMap() {
return beansOfTypeIncludingAncestors(applicationContext, ServiceBean.class);
}
protected ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor() {
return applicationContext.getBean(BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class);
}
protected Map<String, ProtocolConfig> getProtocolConfigsBeanMap() {
return beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class);
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\metadata\AbstractDubboMetadata.java | 1 |
请完成以下Java代码 | public void setQtyCount (final @Nullable BigDecimal QtyCount)
{
set_Value (COLUMNNAME_QtyCount, QtyCount);
}
@Override
public BigDecimal getQtyCount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInternalUse (final @Nullable BigDecimal QtyInternalUse)
{
set_Value (COLUMNNAME_QtyInternalUse, QtyInternalUse);
}
@Override
public BigDecimal getQtyInternalUse()
{ | final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInternalUse);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setRenderedQRCode (final @Nullable java.lang.String RenderedQRCode)
{
set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode);
}
@Override
public java.lang.String getRenderedQRCode()
{
return get_ValueAsString(COLUMNNAME_RenderedQRCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_InventoryLine_HU.java | 1 |
请完成以下Java代码 | protected void closeCallUnauthenticated(final ServerCall<?, ?> call, final AuthenticationException aex) {
log.debug(UNAUTHENTICATED_DESCRIPTION, aex);
call.close(Status.UNAUTHENTICATED.withCause(aex).withDescription(UNAUTHENTICATED_DESCRIPTION), new Metadata());
}
/**
* Close the call with {@link Status#PERMISSION_DENIED}.
*
* @param call The call to close.
* @param aex The exception that was the cause.
*/
protected void closeCallAccessDenied(final ServerCall<?, ?> call, final AccessDeniedException aex) {
log.debug(ACCESS_DENIED_DESCRIPTION, aex);
call.close(Status.PERMISSION_DENIED.withCause(aex).withDescription(ACCESS_DENIED_DESCRIPTION), new Metadata());
}
/**
* Server call listener that catches and handles exceptions in {@link #onHalfClose()}.
*
* @param <ReqT> The type of the request.
* @param <RespT> The type of the response.
*/
private class ExceptionTranslatorServerCallListener<ReqT, RespT> extends SimpleForwardingServerCallListener<ReqT> {
private final ServerCall<ReqT, RespT> call;
protected ExceptionTranslatorServerCallListener(final Listener<ReqT> delegate,
final ServerCall<ReqT, RespT> call) { | super(delegate);
this.call = call;
}
@Override
// Unary calls error out here
public void onHalfClose() {
try {
super.onHalfClose();
} catch (final AuthenticationException aex) {
closeCallUnauthenticated(this.call, aex);
} catch (final AccessDeniedException aex) {
closeCallAccessDenied(this.call, aex);
}
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\interceptors\ExceptionTranslatingServerInterceptor.java | 1 |
请完成以下Java代码 | public List<HistoricProcessInstance> findHistoricProcessInstancesAndVariablesByQueryCriteria(
HistoricProcessInstanceQueryImpl historicProcessInstanceQuery
) {
if (getHistoryManager().isHistoryEnabled()) {
return historicProcessInstanceDataManager.findHistoricProcessInstancesAndVariablesByQueryCriteria(
historicProcessInstanceQuery
);
}
return emptyList();
}
@Override
public List<HistoricProcessInstance> findHistoricProcessInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return historicProcessInstanceDataManager.findHistoricProcessInstancesByNativeQuery(
parameterMap,
firstResult,
maxResults
); | }
@Override
public long findHistoricProcessInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return historicProcessInstanceDataManager.findHistoricProcessInstanceCountByNativeQuery(parameterMap);
}
public HistoricProcessInstanceDataManager getHistoricProcessInstanceDataManager() {
return historicProcessInstanceDataManager;
}
public void setHistoricProcessInstanceDataManager(
HistoricProcessInstanceDataManager historicProcessInstanceDataManager
) {
this.historicProcessInstanceDataManager = historicProcessInstanceDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntityManagerImpl.java | 1 |
请完成以下Java代码 | public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) { | return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedSubgraph\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public void setFirst(T1 first)
{
this.first = first;
}
@Override
public Pair<T1, T2> clone()
{
return new Pair<T1, T2>(first, second);
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Pair))
return false;
Pair pair = (Pair) o;
if (pair.second == null)
if (second == null)
return pair.first.equals(first);
else
return false;
if (second == null)
return false;
return pair.first.equals(first) && pair.second.equals(second);
} | @Override
public int hashCode()
{
int firstHash = 0;
int secondHash = 0;
if (first != null)
firstHash = first.hashCode();
if (second != null)
secondHash = second.hashCode();
return firstHash + secondHash;
}
@Override
public int compareTo(Object o)
{
if (equals(o))
return 0;
return hashCode() - o.hashCode();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\accessories\Pair.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EntityLinkEntityManagerImpl
extends AbstractServiceEngineEntityManager<EntityLinkServiceConfiguration, EntityLinkEntity, EntityLinkDataManager>
implements EntityLinkEntityManager {
public EntityLinkEntityManagerImpl(EntityLinkServiceConfiguration entityLinkServiceConfiguration, EntityLinkDataManager entityLinkDataManager) {
super(entityLinkServiceConfiguration, entityLinkServiceConfiguration.getEngineName(), entityLinkDataManager);
}
@Override
public EntityLinkEntity create() {
EntityLinkEntity entityLinkEntity = super.create();
entityLinkEntity.setCreateTime(getClock().getCurrentTime());
return entityLinkEntity;
}
@Override
public List<EntityLink> findEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType) {
return dataManager.findEntityLinksWithSameRootScopeForScopeIdAndScopeType(scopeId, scopeType, linkType); | }
@Override
public InternalEntityLinkQuery<EntityLinkEntity> createInternalEntityLinkQuery() {
return new InternalEntityLinkQueryImpl<>(dataManager::findEntityLinksByQuery, dataManager::findEntityLinkByQuery);
}
@Override
public void deleteEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
dataManager.deleteEntityLinksByScopeIdAndScopeType(scopeId, scopeType);
}
@Override
public void deleteEntityLinksByRootScopeIdAndType(String scopeId, String scopeType) {
dataManager.deleteEntityLinksByRootScopeIdAndType(scopeId, scopeType);
}
} | repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\EntityLinkEntityManagerImpl.java | 2 |
请完成以下Java代码 | public void setApp(String app) {
this.app = app;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port; | }
public String getApiName() {
return apiName;
}
public void setApiName(String apiName) {
this.apiName = apiName;
}
public List<ApiPredicateItemVo> getPredicateItems() {
return predicateItems;
}
public void setPredicateItems(List<ApiPredicateItemVo> predicateItems) {
this.predicateItems = predicateItems;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\api\AddApiReqVo.java | 1 |
请完成以下Java代码 | public I_C_BPartner getC_BPartner()
{
return qtyReportEvent.getC_BPartner();
}
@Override
public boolean isContractedProduct()
{
final String contractLine_uuid = qtyReportEvent.getContractLine_UUID();
return !Check.isEmpty(contractLine_uuid, true);
}
@Override
public I_M_Product getM_Product()
{
return qtyReportEvent.getM_Product();
}
@Override
public int getProductId()
{
return qtyReportEvent.getM_Product_ID();
}
@Override
public I_C_UOM getC_UOM()
{
return qtyReportEvent.getC_UOM();
}
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
return qtyReportEvent.getC_Flatrate_Term();
}
@Override
public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry()
{
return InterfaceWrapperHelper.create(qtyReportEvent.getC_Flatrate_DataEntry(), I_C_Flatrate_DataEntry.class);
}
@Override
public Object getWrappedModel()
{
return qtyReportEvent;
}
@Override
public Timestamp getDate()
{ | return qtyReportEvent.getDatePromised();
}
@Override
public BigDecimal getQty()
{
return qtyReportEvent.getQtyPromised();
}
@Override
public void setM_PricingSystem_ID(final int M_PricingSystem_ID)
{
qtyReportEvent.setM_PricingSystem_ID(M_PricingSystem_ID);
}
@Override
public void setM_PriceList_ID(final int M_PriceList_ID)
{
qtyReportEvent.setM_PriceList_ID(M_PriceList_ID);
}
@Override
public void setCurrencyId(final CurrencyId currencyId)
{
qtyReportEvent.setC_Currency_ID(CurrencyId.toRepoId(currencyId));
}
@Override
public void setPrice(final BigDecimal price)
{
qtyReportEvent.setPrice(price);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMPricingAware_QtyReportEvent.java | 1 |
请完成以下Java代码 | ShipmentCosts getCreateShipmentCosts(final AcctSchema as)
{
final CostDetailCreateResultsList results;
if (isReversalLine())
{
results = services.createReversalCostDetails(CostDetailReverseRequest.builder()
.acctSchemaId(as.getId())
.reversalDocumentRef(CostingDocumentRef.ofShipmentLineId(get_ID()))
.initialDocumentRef(CostingDocumentRef.ofShipmentLineId(getReversalLine_ID()))
.date(getDateAcctAsInstant())
.build());
}
else
{
results = services.createCostDetail(
CostDetailCreateRequest.builder()
.acctSchemaId(as.getId())
.clientId(getClientId())
.orgId(getOrgId())
.productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId())
.documentRef(CostingDocumentRef.ofShipmentLineId(get_ID()))
.qty(getQty().negateIf(isMaterialReturn()))
.amt(CostAmount.zero(as.getCurrencyId())) // expect to be calculated
.currencyConversionContext(getCurrencyConversionContext(as))
.date(getDateAcctAsInstant())
.build());
}
return ShipmentCosts.extractAccountableFrom(results, as);
}
private CurrencyConversionContext getCurrencyConversionContext(final AcctSchema as)
{
return getDoc().getCurrencyConversionContext(as);
}
@Override
protected OrderId getSalesOrderId()
{
final I_M_InOutLine inoutLine = getInOutLine();
return OrderId.ofRepoIdOrNull(inoutLine.getC_OrderSO_ID());
}
@Nullable
public BPartnerId getBPartnerId(@NonNull final CostElementId costElementId)
{
final ImmutableSet<BPartnerId> costBPartnerIds = inoutCosts.stream()
.filter(inoutCost -> CostElementId.equals(inoutCost.getCostElementId(), costElementId))
.map(InOutCost::getBpartnerId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet()); | final BPartnerId costBPartnerId = CollectionUtils.singleElementOrNull(costBPartnerIds);
if (costBPartnerId != null)
{
return costBPartnerId;
}
else
{
return getBPartnerId();
}
}
@Nullable
public BPartnerLocationId getBPartnerLocationId(@NonNull final CostElementId costElementId)
{
final BPartnerLocationId bpartnerLocationId = getDoc().getBPartnerLocationId();
if (bpartnerLocationId == null)
{
return null;
}
final BPartnerId bpartnerId = getBPartnerId(costElementId);
if (BPartnerId.equals(bpartnerLocationId.getBpartnerId(), bpartnerId))
{
return bpartnerLocationId;
}
else
{
return null;
}
}
private boolean isMaterialReturn() {return getInOutDocBaseType().isReturn();}
@NonNull
private InOutDocBaseType getInOutDocBaseType() {return getDoc().getInOutDocBaseType();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_InOut.java | 1 |
请完成以下Java代码 | public final class NullQueueProcessorsExecutor implements IQueueProcessorsExecutor
{
public static final NullQueueProcessorsExecutor instance = new NullQueueProcessorsExecutor();
private NullQueueProcessorsExecutor()
{
super();
}
@Override
public void removeQueueProcessor(final int queueProcessorId)
{
}
@Override
public void addQueueProcessor(final I_C_Queue_Processor processorDef) | {
// nothing
}
@Override
public void shutdown()
{
// nothing
}
@Override
public IQueueProcessor getQueueProcessor(final QueueProcessorId queueProcessorId)
{
// nothing
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\NullQueueProcessorsExecutor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Builder setOutputType(final OutputType outputType)
{
this.outputType = outputType;
return this;
}
public Builder setType(@NonNull final ProcessType type)
{
this.type = type;
return this;
}
public Builder setJSONPath(final String JSONPath)
{
this.JSONPath = JSONPath;
return this;
}
public Builder setRecord(final int AD_Table_ID, final int Record_ID)
{
this.AD_Table_ID = AD_Table_ID;
this.Record_ID = Record_ID;
return this;
}
public Builder setReportTemplatePath(final String reportTemplatePath)
{
this.reportTemplatePath = reportTemplatePath;
return this;
}
public Builder setSQLStatement(final String sqlStatement)
{
this.sqlStatement = sqlStatement;
return this;
}
public Builder setApplySecuritySettings(final boolean applySecuritySettings)
{
this.applySecuritySettings = applySecuritySettings; | return this;
}
private ImmutableList<ProcessInfoParameter> getProcessInfoParameters()
{
return Services.get(IADPInstanceDAO.class).retrieveProcessInfoParameters(pinstanceId)
.stream()
.map(this::transformProcessInfoParameter)
.collect(ImmutableList.toImmutableList());
}
private ProcessInfoParameter transformProcessInfoParameter(final ProcessInfoParameter piParam)
{
//
// Corner case: REPORT_SQL_QUERY
// => replace @AD_PInstance_ID@ placeholder with actual value
if (ReportConstants.REPORT_PARAM_SQL_QUERY.equals(piParam.getParameterName()))
{
final String parameterValue = piParam.getParameterAsString();
if (parameterValue != null)
{
final String parameterValueEffective = parameterValue.replace(ReportConstants.REPORT_PARAM_SQL_QUERY_AD_PInstance_ID_Placeholder, String.valueOf(pinstanceId.getRepoId()));
return ProcessInfoParameter.of(ReportConstants.REPORT_PARAM_SQL_QUERY, parameterValueEffective);
}
}
//
// Default: don't touch the original parameter
return piParam;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\server\ReportContext.java | 2 |
请完成以下Java代码 | private XWPFDocument replaceText(XWPFDocument doc, String originalText, String updatedText) {
replaceTextInParagraphs(doc.getParagraphs(), originalText, updatedText);
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
replaceTextInParagraphs(cell.getParagraphs(), originalText, updatedText);
}
}
}
return doc;
}
private void replaceTextInParagraphs(List<XWPFParagraph> paragraphs, String originalText, String updatedText) {
paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText));
}
private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) { | List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
if (text != null && text.contains(originalText)) {
String updatedRunText = text.replace(originalText, updatedText);
run.setText(updatedRunText, 0);
}
}
}
private void saveFile(String filePath, XWPFDocument doc) throws IOException {
try (FileOutputStream out = new FileOutputStream(filePath)) {
doc.write(out);
}
}
} | repos\tutorials-master\apache-poi-2\src\main\java\com\baeldung\poi\replacevariables\DocxNaiveTextReplacer.java | 1 |
请完成以下Java代码 | public class WindowHeaderNotice extends JPanel
{
/**
*
*/
private static final long serialVersionUID = -914277060790906131L;
private final JLabel label = new JLabel();
public WindowHeaderNotice()
{
super();
//
// Init components & layout
{
this.setBackground(AdempierePLAF.getColor("WindowHeaderNotice.background", "red", Color.RED));
this.setMinimumSize(new Dimension(100, 50));
label.setForeground(AdempierePLAF.getColor("WindowHeaderNotice.foreground", "white", Color.WHITE));
this.add(label);
}
//
// Load from context
load();
}
public void setNotice(final String notice)
{
label.setText(notice);
}
public String getNotice()
{
return label.getText();
}
/**
* Load status from context
*/
public void load()
{
final Properties ctx = Env.getCtx(); | // FRESH-352: check if we shall override the default background color which we set in the constructor
final String windowHeaderNoticeBGColorStr = Env.getContext(ctx, Env.CTXNAME_UI_WindowHeader_Notice_BG_COLOR);
if (!Check.isEmpty(windowHeaderNoticeBGColorStr, true))
{
final Color backgroundColor = Colors.toColor(windowHeaderNoticeBGColorStr);
if (backgroundColor != null)
{
this.setBackground(backgroundColor);
}
}
final String windowHeaderNoticeFGColorStr = Env.getContext(ctx, Env.CTXNAME_UI_WindowHeader_Notice_FG_COLOR);
if (!Check.isEmpty(windowHeaderNoticeBGColorStr, true))
{
final Color foregroundColor = Colors.toColor(windowHeaderNoticeFGColorStr);
if (foregroundColor != null)
{
label.setForeground(foregroundColor);
}
}
final String windowHeaderNotice = Env.getContext(ctx, Env.CTXNAME_UI_WindowHeader_Notice_Text);
if (!Check.isEmpty(windowHeaderNotice, true) && !"-".equals(windowHeaderNotice))
{
setNotice(windowHeaderNotice);
setVisible(true);
}
else
{
setNotice("");
setVisible(false);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\WindowHeaderNotice.java | 1 |
请完成以下Java代码 | public class LicenseKeyDataDto {
public static final String SERIALIZED_VALID_UNTIL = "valid-until";
public static final String SERIALIZED_IS_UNLIMITED = "unlimited";
protected String customer;
protected String type;
@JsonProperty(value = SERIALIZED_VALID_UNTIL)
protected String validUntil;
@JsonProperty(value = SERIALIZED_IS_UNLIMITED)
protected Boolean isUnlimited;
protected Map<String, String> features;
protected String raw;
public LicenseKeyDataDto(String customer, String type, String validUntil, Boolean isUnlimited, Map<String, String> features, String raw) {
this.customer = customer;
this.type = type;
this.validUntil = validUntil;
this.isUnlimited = isUnlimited;
this.features = features;
this.raw = raw;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValidUntil() {
return validUntil;
}
public void setValidUntil(String validUntil) {
this.validUntil = validUntil;
}
public Boolean isUnlimited() {
return isUnlimited;
}
public void setUnlimited(Boolean isUnlimited) {
this.isUnlimited = isUnlimited;
}
public Map<String, String> getFeatures() { | return features;
}
public void setFeatures(Map<String, String> features) {
this.features = features;
}
public String getRaw() {
return raw;
}
public void setRaw(String raw) {
this.raw = raw;
}
public static LicenseKeyDataDto fromEngineDto(LicenseKeyData other) {
return new LicenseKeyDataDto(
other.getCustomer(),
other.getType(),
other.getValidUntil(),
other.isUnlimited(),
other.getFeatures(),
other.getRaw());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\LicenseKeyDataDto.java | 1 |
请完成以下Java代码 | public TimerJobQuery jobWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
// sorting //////////////////////////////////////////
@Override
public TimerJobQuery orderByJobDuedate() {
return orderBy(JobQueryProperty.DUEDATE);
}
@Override
public TimerJobQuery orderByExecutionId() {
return orderBy(JobQueryProperty.EXECUTION_ID);
}
@Override
public TimerJobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
@Override
public TimerJobQuery orderByProcessInstanceId() {
return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID);
}
@Override
public TimerJobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
@Override
public TimerJobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getTimerJobEntityManager()
.findTimerJobCountByQueryCriteria(this);
}
@Override
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getTimerJobEntityManager()
.findTimerJobsByQueryCriteria(this, page);
}
// getters ////////////////////////////////////////// | public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\TimerJobQueryImpl.java | 1 |
请完成以下Java代码 | public <T> T newInstance(final Class<T> modelClass, final Object contextProvider)
{
return InterfaceWrapperHelper.newInstance(modelClass, contextProvider);
}
@Override
public void initHUStorages(final I_M_HU hu)
{
// nothing
}
@Override
public void initHUItemStorages(final I_M_HU_Item item)
{
// nothing
}
@Override
public I_M_HU_Storage retrieveStorage(final I_M_HU hu, @NonNull final ProductId productId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU_Storage.class, hu)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_Storage.COLUMNNAME_M_HU_ID, hu.getM_HU_ID())
.addEqualsFilter(I_M_HU_Storage.COLUMNNAME_M_Product_ID, productId)
.create()
.firstOnly(I_M_HU_Storage.class);
}
@Override
public void save(final I_M_HU_Storage storage)
{
InterfaceWrapperHelper.save(storage);
}
@Override
public List<I_M_HU_Storage> retrieveStorages(final I_M_HU hu)
{
final List<I_M_HU_Storage> huStorages = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU_Storage.class, hu)
.filter(new EqualsQueryFilter<I_M_HU_Storage>(I_M_HU_Storage.COLUMNNAME_M_HU_ID, hu.getM_HU_ID()))
.create()
.setOnlyActiveRecords(true)
.list(I_M_HU_Storage.class);
// Optimization: set parent link
for (final I_M_HU_Storage huStorage : huStorages)
{
huStorage.setM_HU(hu);
}
return huStorages;
}
@Override
public I_M_HU_Item_Storage retrieveItemStorage(final I_M_HU_Item huItem, @NonNull final ProductId productId)
{
return Services.get(IQueryBL.class).createQueryBuilder(I_M_HU_Item_Storage.class, huItem)
.filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_ID, huItem.getM_HU_Item_ID()))
.filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_Product_ID, productId))
.create()
.setOnlyActiveRecords(true)
.firstOnly(I_M_HU_Item_Storage.class);
}
@Override
public List<I_M_HU_Item_Storage> retrieveItemStorages(final I_M_HU_Item huItem)
{
final IQueryBuilder<I_M_HU_Item_Storage> queryBuilder = Services.get(IQueryBL.class) | .createQueryBuilder(I_M_HU_Item_Storage.class, huItem)
.filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_ID, huItem.getM_HU_Item_ID()));
queryBuilder.orderBy()
.addColumn(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_Storage_ID); // predictive order
final List<I_M_HU_Item_Storage> huItemStorages = queryBuilder
.create()
.setOnlyActiveRecords(true)
.list(I_M_HU_Item_Storage.class);
// Optimization: set parent link
for (final I_M_HU_Item_Storage huItemStorage : huItemStorages)
{
huItemStorage.setM_HU_Item(huItem);
}
return huItemStorages;
}
@Override
public void save(final I_M_HU_Item_Storage storageLine)
{
InterfaceWrapperHelper.save(storageLine);
}
@Override
public void save(final I_M_HU_Item item)
{
InterfaceWrapperHelper.save(item);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUStorageDAO.java | 1 |
请完成以下Java代码 | public CaseInstance start() {
return cmmnRuntimeService.startCaseInstance(this);
}
@Override
public CaseInstance startAsync() {
return cmmnRuntimeService.startCaseInstanceAsync(this);
}
@Override
public CaseInstance startWithForm() {
this.startWithForm = true;
return cmmnRuntimeService.startCaseInstance(this);
}
@Override
public String getCaseDefinitionId() {
return caseDefinitionId;
}
@Override
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
@Override
public String getCaseDefinitionParentDeploymentId() {
return caseDefinitionParentDeploymentId;
}
@Override
public String getPredefinedCaseInstanceId() {
return predefinedCaseInstanceId;
}
@Override
public String getName() {
return name;
}
@Override
public String getBusinessKey() {
return businessKey;
}
@Override
public String getBusinessStatus() {
return businessStatus;
}
@Override
public Map<String, Object> getVariables() {
return variables;
}
@Override
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getOwner() {
return ownerId;
}
@Override
public String getAssignee() {
return assigneeId;
}
@Override
public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId;
}
@Override
public String getOutcome() {
return outcome;
} | @Override
public Map<String, Object> getStartFormVariables() {
return startFormVariables;
}
@Override
public String getCallbackId() {
return this.callbackId;
}
@Override
public String getCallbackType() {
return this.callbackType;
}
@Override
public String getReferenceId() {
return referenceId;
}
@Override
public String getReferenceType() {
return referenceType;
}
@Override
public String getParentId() {
return this.parentId;
}
@Override
public boolean isFallbackToDefaultTenant() {
return this.fallbackToDefaultTenant;
}
@Override
public boolean isStartWithForm() {
return this.startWithForm;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceBuilderImpl.java | 1 |
请完成以下Java代码 | private ArrayKey mkGroupingKey(@NonNull final OLCand candidate)
{
if (aggregationInfo.getGroupByColumns().isEmpty())
{
// each candidate results in its own order line
return Util.mkKey(candidate.getId());
}
final ArrayKeyBuilder groupingValues = ArrayKey.builder()
.appendAll(groupingValuesProviders.provideLineGroupingValues(candidate));
for (final OLCandAggregationColumn column : aggregationInfo.getColumns())
{
if (!column.isGroupByColumn())
{
// we don't group by the current column, so all different values result in their own order lines
groupingValues.append(candidate.getValueByColumn(column));
}
else if (column.getGranularity() != null)
{
// create a grouping key based on the granularity level
final Granularity granularity = column.getGranularity();
final Timestamp timestamp = (Timestamp)candidate.getValueByColumn(column);
final long groupingValue = truncateDateByGranularity(timestamp, granularity).getTime();
groupingValues.append(groupingValue);
}
}
return groupingValues.build();
}
private static Timestamp truncateDateByGranularity(final Timestamp date, final Granularity granularity)
{
if (granularity == Granularity.Day)
{ | return TimeUtil.trunc(date, TimeUtil.TRUNC_DAY);
}
else if (granularity == Granularity.Week)
{
return TimeUtil.trunc(date, TimeUtil.TRUNC_WEEK);
}
else if (granularity == Granularity.Month)
{
return TimeUtil.trunc(date, TimeUtil.TRUNC_MONTH);
}
else
{
throw new AdempiereException("Unknown granularity: " + granularity);
}
}
@NonNull
private List<OLCand> getEligibleOLCand()
{
final GetEligibleOLCandRequest request = GetEligibleOLCandRequest.builder()
.aggregationInfo(aggregationInfo)
.orderDefaults(orderDefaults)
.selection(selectionId)
.asyncBatchId(asyncBatchId)
.build();
return olCandProcessingHelper.getOLCandsForProcessing(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandsProcessorExecutor.java | 1 |
请完成以下Java代码 | public void delete(JobEntity entity, boolean fireDeleteEvent) {
if (entity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) {
CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById(
entity.getExecutionId()
);
if (isExecutionRelatedEntityCountEnabled(executionEntity)) {
executionEntity.setJobCount(executionEntity.getJobCount() - 1);
}
}
super.delete(entity, fireDeleteEvent);
}
/**
* Removes the job's execution's reference to this job, if the job has an associated execution.
* Subclasses may override to provide custom implementations.
*/
protected void removeExecutionLink(JobEntity jobEntity) {
if (jobEntity.getExecutionId() != null) {
ExecutionEntity execution = getExecutionEntityManager().findById(jobEntity.getExecutionId());
if (execution != null) {
execution.getJobs().remove(jobEntity);
}
}
} | /**
* Deletes a the byte array used to store the exception information. Subclasses may override
* to provide custom implementations.
*/
protected void deleteExceptionByteArrayRef(JobEntity jobEntity) {
ByteArrayRef exceptionByteArrayRef = jobEntity.getExceptionByteArrayRef();
if (exceptionByteArrayRef != null) {
exceptionByteArrayRef.delete();
}
}
public JobDataManager getJobDataManager() {
return jobDataManager;
}
public void setJobDataManager(JobDataManager jobDataManager) {
this.jobDataManager = jobDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\JobEntityManagerImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class Aggregation
{
private final AggregationId id;
private final String tableName;
private final ImmutableList<AggregationItem> items;
@Builder
public Aggregation(
@Nullable final AggregationId id,
@NonNull final String tableName,
@NonNull @Singular final Collection<AggregationItem> items)
{
Check.assumeNotEmpty(tableName, "tableName not empty");
Check.assumeNotEmpty(items, "items not empty for aggregationId={} (tableName={})", id, tableName);
this.id = id;
this.tableName = tableName;
this.items = ImmutableList.copyOf(items);
}
public boolean hasColumnName(final String columnName)
{
Check.assumeNotEmpty(columnName, "columnName not empty");
for (final AggregationItem item : items)
{
if (item.getType() != Type.ModelColumn)
{
continue;
}
if (!columnName.equals(item.getColumnName())) | {
continue;
}
return true;
}
return false;
}
public boolean hasInvoicePerShipmentAttribute()
{
return getItems().stream()
.filter(item -> item.getType() == Type.Attribute && item.getAttribute() != null)
.anyMatch(item -> ("@" + I_M_InOut.COLUMNNAME_M_InOut_ID + "@").equals(item.getAttribute().evaluate(Evaluatees.empty())));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\Aggregation.java | 2 |
请完成以下Java代码 | private Object getValue(final JTable table, final int rowIndexView)
{
final int columnIndexView_Value = table.convertColumnIndexToView(UIDefaultsTableModel.COLUMNINDEX_Value);
final Object value = table.getValueAt(rowIndexView, columnIndexView_Value);
return value;
}
private final void setValue(final JTable table, final int rowIndexView, final Object value, final Object valueOld)
{
final UIDefaultsTableModel tableModel = (UIDefaultsTableModel)table.getModel();
final int rowIndexModel = table.convertRowIndexToModel(rowIndexView);
final Set<Object> similarKeysToUpdate = getSimilarKeysToUpdate(table, valueOld, rowIndexModel);
tableModel.setValueAt(value, rowIndexModel, UIDefaultsTableModel.COLUMNINDEX_Value);
for (final Object key : similarKeysToUpdate)
{
tableModel.setValue(key, value);
}
}
private Set<Object> getSimilarKeysToUpdate(final JTable table, final Object valueOld, final int rowIndexModel)
{
final UIDefaultsTableModel tableModel = (UIDefaultsTableModel)table.getModel();
final Set<Object> keysWithSameValue = tableModel.getKeysWithSameValue(valueOld, rowIndexModel);
if (keysWithSameValue.isEmpty())
{
return Collections.emptySet();
}
final JXList list = new JXList(keysWithSameValue.toArray());
list.setVisibleRowCount(20);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
final Object[] params = new Object[] {
"Following keys have the same value. Do you want to change them too?",
new JScrollPane(list) };
final int answer = JOptionPane.showConfirmDialog(
table, // parentComponent
params, // message
"Change similar keys?", // title
JOptionPane.YES_NO_OPTION // messageType
);
if (answer != JOptionPane.YES_OPTION)
{
return Collections.emptySet();
}
final Set<Object> keysToUpdate = new LinkedHashSet<>(Arrays.asList(list.getSelectedValues()));
return keysToUpdate;
}
}
/**
* {@link RowFilter} which includes only rows which contains a given <code>text</code>. | *
* @author tsa
*
*/
static class FullTextSearchRowFilter extends RowFilter<TableModel, Integer>
{
public static FullTextSearchRowFilter ofText(final String text)
{
if (Check.isEmpty(text, true))
{
return null;
}
else
{
return new FullTextSearchRowFilter(text);
}
}
private final String textUC;
private FullTextSearchRowFilter(final String text)
{
super();
textUC = text.toUpperCase();
}
@Override
public boolean include(final javax.swing.RowFilter.Entry<? extends TableModel, ? extends Integer> entry)
{
for (int i = entry.getValueCount() - 1; i >= 0; i--)
{
String entryValue = entry.getStringValue(i);
if (entryValue == null || entryValue.isEmpty())
{
continue;
}
entryValue = entryValue.toUpperCase();
if (entryValue.indexOf(textUC) >= 0)
{
return true;
}
}
return false;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\plaf\UIDefaultsEditorDialog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AppConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setPackagesToScan("com.baeldung.spring.data.jpa.joinquery.entities"
, "com.baeldung.spring.data.jpa.joinquery.DTO"
, "com.baeldung.spring.data.jpa.joinquery.repositories");
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
emf.setJpaProperties(getHibernateProperties());
return emf;
} | @Bean
public JpaTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory.getObject());
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return properties;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\AppConfig.java | 2 |
请完成以下Java代码 | public class ReflectionsApp {
public Set<Class<? extends Scanner>> getReflectionsSubTypes() {
Reflections reflections = new Reflections("org.reflections");
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
public Set<Class<?>> getJDKFunctinalInterfaces() {
Reflections reflections = new Reflections("java.util.function");
Set<Class<?>> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class);
return typesSet;
}
public Set<Method> getDateDeprecatedMethods() {
Reflections reflections = new Reflections(Date.class, new MethodAnnotationsScanner());
Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class);
return deprecatedMethodsSet;
}
@SuppressWarnings("rawtypes")
public Set<Constructor> getDateDeprecatedConstructors() {
Reflections reflections = new Reflections(Date.class, new MethodAnnotationsScanner());
Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class);
return constructorsSet;
}
public Set<Method> getMethodsWithDateParam() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class);
return methodsSet;
} | public Set<Method> getMethodsWithVoidReturn() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsReturn(void.class);
return methodsSet;
}
public Set<String> getPomXmlPaths() {
Reflections reflections = new Reflections(new ResourcesScanner());
Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml"));
return resourcesSet;
}
public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() {
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections"))
.setScanners(new SubTypesScanner()));
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
} | repos\tutorials-master\libraries-jdk8\src\main\java\reflections\ReflectionsApp.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AsyncComponent {
@Async
public void asyncMethodWithVoidReturnType() {
System.out.println("Execute method asynchronously. "
+ Thread.currentThread().getName());
}
@Async
public CompletableFuture<String> asyncMethodWithReturnType() {
System.out.println("Execute method asynchronously - "
+ Thread.currentThread().getName());
try {
Thread.sleep(5000);
return CompletableFuture.completedFuture("hello world !!!!");
} catch (InterruptedException e) { | return CompletableFuture.failedFuture(e);
}
}
@Async("threadPoolTaskExecutor")
public void asyncMethodWithConfiguredExecutor() {
System.out.println("Execute method with configured executor - "
+ Thread.currentThread().getName());
}
@Async
public void asyncMethodWithExceptions() throws Exception {
throw new Exception("Throw message from asynchronous method. ");
}
} | repos\tutorials-master\spring-scheduling\src\main\java\com\baeldung\async\AsyncComponent.java | 2 |
请完成以下Java代码 | public static Object[] getUIDefaults()
{
return new Object[] {
//
// Label (and also editor's labels) border
// NOTE: we add a small space on top in order to have the label text aligned on same same base line as the text from the right text field.
AdempiereLabelUI.KEY_Border, new BorderUIResource(BorderFactory.createEmptyBorder(3, 0, 0, 0))
//
// Editor button align (i.e. that small button of an editor field which is opening the Info Window)
, VEditorDialogButtonAlign.DEFAULT_EditorUI, VEditorDialogButtonAlign.Right
// , VEditorDialogButtonAlign.createUIKey("VNumber"), VEditorDialogButtonAlign.Hide
// , VEditorDialogButtonAlign.createUIKey("VDate"), VEditorDialogButtonAlign.Hide
// , VEditorDialogButtonAlign.createUIKey("VURL"), VEditorDialogButtonAlign.Right // i.e. the online button
//
// Editor height
, KEY_VEditor_Height, DEFAULT_VEditor_Height
// | // VButton editor
, "VButton.Action.textColor", AdempierePLAF.createActiveValueProxy("black", Color.BLACK)
, "VButton.Posted.textColor", new ColorUIResource(Color.MAGENTA)
};
}
public static final int getVEditorHeight()
{
return AdempierePLAF.getInt(KEY_VEditor_Height, DEFAULT_VEditor_Height);
}
public static final void installMinMaxSizes(final JComponent comp)
{
final int height = VEditorUI.getVEditorHeight();
comp.setMinimumSize(new Dimension(30, height));
comp.setMaximumSize(new Dimension(Integer.MAX_VALUE, height));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\VEditorUI.java | 1 |
请完成以下Java代码 | public Optional<InvoiceRow> getInvoiceRowByInvoiceId(
@NonNull final InvoiceId invoiceId,
@NonNull final ZonedDateTime evaluationDate)
{
final List<InvoiceRow> invoiceRows = getInvoiceRowsListByInvoiceId(ImmutableList.of(invoiceId), evaluationDate);
if (invoiceRows.isEmpty())
{
return Optional.empty();
}
else if (invoiceRows.size() == 1)
{
return Optional.of(invoiceRows.get(0));
}
else
{
throw new AdempiereException("Expected only one row for " + invoiceId + " but got " + invoiceRows);
}
}
public List<PaymentRow> getPaymentRowsListByPaymentId(
@NonNull final Collection<PaymentId> paymentIds,
@NonNull final ZonedDateTime evaluationDate)
{
if (paymentIds.isEmpty())
{
return ImmutableList.of();
}
final PaymentToAllocateQuery query = PaymentToAllocateQuery.builder()
.evaluationDate(evaluationDate)
.additionalPaymentIdsToInclude(paymentIds)
.build();
return paymentAllocationRepo.retrievePaymentsToAllocate(query)
.stream()
.map(this::toPaymentRow)
.collect(ImmutableList.toImmutableList()); | }
public Optional<PaymentRow> getPaymentRowByPaymentId(
@NonNull final PaymentId paymentId,
@NonNull final ZonedDateTime evaluationDate)
{
final List<PaymentRow> paymentRows = getPaymentRowsListByPaymentId(ImmutableList.of(paymentId), evaluationDate);
if (paymentRows.isEmpty())
{
return Optional.empty();
}
else if (paymentRows.size() == 1)
{
return Optional.of(paymentRows.get(0));
}
else
{
throw new AdempiereException("Expected only one row for " + paymentId + " but got " + paymentRows);
}
}
@Value
@Builder
private static class InvoiceRowLoadingContext
{
@NonNull ZonedDateTime evaluationDate;
@NonNull ImmutableSet<InvoiceId> invoiceIdsWithServiceInvoiceAlreadyGenetated;
public boolean isServiceInvoiceAlreadyGenerated(@NonNull final InvoiceId invoiceId)
{
return invoiceIdsWithServiceInvoiceAlreadyGenetated.contains(invoiceId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\PaymentAndInvoiceRowsRepo.java | 1 |
请完成以下Java代码 | private static boolean isExcludedSimpleValueType(Class<?> type) {
// Same as BeanUtils.isSimpleValueType except for CharSequence and Number
return (Void.class != type && void.class != type &&
(ClassUtils.isPrimitiveOrWrapper(type) ||
Date.class.isAssignableFrom(type) ||
Temporal.class.isAssignableFrom(type) ||
URI.class == type ||
URL.class == type ||
Locale.class == type ||
Class.class == type));
}
@Override
public Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) {
Object source = environment.getSource();
if (source == null) {
throw new IllegalStateException(formatArgumentError(parameter,
"was not recognized by any resolver and there is no source/parent either. " + | "Please, refer to the documentation for the full list of supported parameters."));
}
if (!parameter.getParameterType().isInstance(source)) {
throw new IllegalStateException(formatArgumentError(parameter,
"does not match the source Object type '" + source.getClass() + "'."));
}
return source;
}
private static String formatArgumentError(MethodParameter param, String message) {
return "Parameter [" + param.getParameterIndex() + "] in " +
param.getExecutable().toGenericString() + (StringUtils.hasText(message) ? ": " + message : "");
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\SourceMethodArgumentResolver.java | 1 |
请完成以下Java代码 | public void deleteByteArrayById(String byteArrayEntityId) {
getDbEntityManager().delete(ByteArrayEntity.class, "deleteByteArrayNoRevisionCheck", byteArrayEntityId);
}
public void insertByteArray(ByteArrayEntity arr) {
arr.setCreateTime(ClockUtil.getCurrentTime());
getDbEntityManager().insert(arr);
}
public DbOperation addRemovalTimeToByteArraysByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("rootProcessInstanceId", rootProcessInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
return getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateByteArraysByRootProcessInstanceId", parameters);
}
public List<DbOperation> addRemovalTimeToByteArraysByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
// Make individual statements for each entity type that references byte arrays.
// This can lead to query plans that involve less aggressive locking by databases (e.g. DB2).
// See CAM-10360 for reference.
List<DbOperation> operations = new ArrayList<>(); | operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateVariableByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateDecisionInputsByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateDecisionOutputsByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateJobLogByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateExternalTaskLogByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateAttachmentByteArraysByProcessInstanceId", parameters));
return operations;
}
public DbOperation deleteByteArraysByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(ByteArrayEntity.class, "deleteByteArraysByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayManager.java | 1 |
请完成以下Java代码 | public String[] tag(List<String> wordList)
{
String[] termArray = new String[wordList.size()];
wordList.toArray(termArray);
return tag(termArray);
}
/**
* 在线学习
*
* @param segmentedTaggedSentence 人民日报2014格式的句子
* @return 是否学习成功(失败的原因是参数错误)
*/
public boolean learn(String segmentedTaggedSentence)
{
return learn(POSInstance.create(segmentedTaggedSentence, model.featureMap));
}
/**
* 在线学习
*
* @param wordTags [单词]/[词性]数组
* @return 是否学习成功(失败的原因是参数错误)
*/
public boolean learn(String... wordTags)
{
String[] words = new String[wordTags.length];
String[] tags = new String[wordTags.length]; | for (int i = 0; i < wordTags.length; i++)
{
String[] wordTag = wordTags[i].split("//");
words[i] = wordTag[0];
tags[i] = wordTag[1];
}
return learn(new POSInstance(words, tags, model.featureMap));
}
@Override
protected Instance createInstance(Sentence sentence, FeatureMap featureMap)
{
for (Word word : sentence.toSimpleWordList())
{
if (!model.featureMap.tagSet.contains(word.getLabel()))
throw new IllegalArgumentException("在线学习不可能学习新的标签: " + word + " ;请标注语料库后重新全量训练。");
}
return POSInstance.create(sentence, featureMap);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronPOSTagger.java | 1 |
请完成以下Java代码 | public I_PA_Measure getPA_Measure() throws RuntimeException
{
return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name)
.getPO(getPA_Measure_ID(), get_TrxName()); }
/** Set Measure.
@param PA_Measure_ID
Concrete Performance Measurement
*/
public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_Value (COLUMNNAME_PA_Measure_ID, null);
else
set_Value (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Relative Weight.
@param RelativeWeight
Relative weight of this step (0 = ignored)
*/
public void setRelativeWeight (BigDecimal RelativeWeight)
{
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
}
/** Get Relative Weight. | @return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Goal.java | 1 |
请完成以下Java代码 | public class DeleteHistoricCaseInstancesBulkCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected final List<String> caseInstanceIds;
public DeleteHistoricCaseInstancesBulkCmd(List<String> caseInstanceIds) {
this.caseInstanceIds = caseInstanceIds;
}
@Override
public Void execute(CommandContext commandContext) {
ensureNotEmpty(BadUserRequestException.class, "caseInstanceIds", caseInstanceIds);
// Check if case instances are all closed
commandContext.runWithoutAuthorization(new Callable<Void>() { | @Override
public Void call() throws Exception {
ensureEquals(BadUserRequestException.class, "ClosedCaseInstanceIds",
new HistoricCaseInstanceQueryImpl().closed().caseInstanceIds(new HashSet<String>(caseInstanceIds)).count(), caseInstanceIds.size());
return null;
}
});
commandContext.getOperationLogManager().logCaseInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY,
null, null, Collections.singletonList(new PropertyChange("nrOfInstances", null, caseInstanceIds.size())));
commandContext.getHistoricCaseInstanceManager().deleteHistoricCaseInstancesByIds(caseInstanceIds);
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteHistoricCaseInstancesBulkCmd.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ScriptTask.class, BPMN_ELEMENT_SCRIPT_TASK)
.namespaceUri(BPMN20_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<ScriptTask>() {
public ScriptTask newInstance(ModelTypeInstanceContext instanceContext) {
return new ScriptTaskImpl(instanceContext);
}
});
scriptFormatAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SCRIPT_FORMAT)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
scriptChild = sequenceBuilder.element(Script.class)
.build();
/** camunda extensions */
camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE)
.namespace(CAMUNDA_NS)
.build();
camundaResourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESOURCE)
.namespace(CAMUNDA_NS)
.build();
typeBuilder.build();
}
public ScriptTaskImpl(ModelTypeInstanceContext context) {
super(context);
}
@Override
public ScriptTaskBuilder builder() {
return new ScriptTaskBuilder((BpmnModelInstance) modelInstance, this);
}
public String getScriptFormat() {
return scriptFormatAttribute.getValue(this);
}
public void setScriptFormat(String scriptFormat) {
scriptFormatAttribute.setValue(this, scriptFormat);
}
public Script getScript() {
return scriptChild.getChild(this);
} | public void setScript(Script script) {
scriptChild.setChild(this, script);
}
/** camunda extensions */
public String getCamundaResultVariable() {
return camundaResultVariableAttribute.getValue(this);
}
public void setCamundaResultVariable(String camundaResultVariable) {
camundaResultVariableAttribute.setValue(this, camundaResultVariable);
}
public String getCamundaResource() {
return camundaResourceAttribute.getValue(this);
}
public void setCamundaResource(String camundaResource) {
camundaResourceAttribute.setValue(this, camundaResource);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ScriptTaskImpl.java | 1 |
请完成以下Java代码 | public List<PlainContact> getPlainContacts() {
List<PlainContact> contacts = new ArrayList<>();
PlainContact contact1 = new PlainContact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact2 = new PlainContact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact3 = new PlainContact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plainWithJavaUtilDate") | public List<PlainContactWithJavaUtilDate> getPlainContactsWithJavaUtilDate() {
List<PlainContactWithJavaUtilDate> contacts = new ArrayList<>();
PlainContactWithJavaUtilDate contact1 = new PlainContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact2 = new PlainContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact3 = new PlainContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data\src\main\java\com\baeldung\jsondateformat\ContactController.java | 1 |
请完成以下Java代码 | public String getGlueType() {
return glueType;
}
public void setGlueType(String glueType) {
this.glueType = glueType;
}
public String getGlueSource() {
return glueSource;
}
public void setGlueSource(String glueSource) {
this.glueSource = glueSource;
}
public String getGlueRemark() {
return glueRemark;
}
public void setGlueRemark(String glueRemark) {
this.glueRemark = glueRemark;
} | public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLogGlue.java | 1 |
请完成以下Java代码 | public String getCdtrNames()
{
final TransactionParty2 party = entryDtls.getRltdPties();
if (party != null && party.getDbtr() != null)
{
final PartyIdentification32 cdtr = party.getCdtr();
return cdtr.getNm();
}
return null;
}
@Override
protected @Nullable String getUnstructuredRemittanceInfo(final @NonNull String delimiter)
{
final RemittanceInformation5 rmtInf = entryDtls.getRmtInf();
if(rmtInf == null)
{
return null;
}
return String.join(delimiter, rmtInf.getUstrd());
} | @Override
protected @NonNull String getLineDescription(final @NonNull String delimiter)
{
return entryDtls.getAddtlTxInf();
}
@Nullable
@Override
public String getCcy()
{
return entryDtls.getAmtDtls().getInstdAmt().getAmt().getCcy();
}
/**
* @return true if this is a "credit" line (i.e. we get money)
*/
@Override
public boolean isCRDT()
{
final TransactionParty2 party = entryDtls.getRltdPties();
return party.getCdtr() != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\TransactionDtls2Wrapper.java | 1 |
请完成以下Java代码 | public Date getCreateTime() {
return createTime;
}
public UserDetailVO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
public Integer getDeleted() {
return deleted;
}
public UserDetailVO setDeleted(Integer deleted) {
this.deleted = deleted;
return this;
}
public Integer getTenantId() {
return tenantId;
}
public UserDetailVO setTenantId(Integer tenantId) {
this.tenantId = tenantId;
return this; | }
@Override
public String toString() {
return "UserDetailVO{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender=" + gender +
", createTime=" + createTime +
", deleted=" + deleted +
", tenantId=" + tenantId +
'}';
}
} | repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-plus-tenant\src\main\java\cn\iocoder\springboot\lab12\mybatis\vo\UserDetailVO.java | 1 |
请完成以下Java代码 | private Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
for (int i = 0; i < newSol.getDefaultGeneLength(); i++) {
if (Math.random() <= uniformRate) {
newSol.setSingleGene(i, indiv1.getSingleGene(i));
} else {
newSol.setSingleGene(i, indiv2.getSingleGene(i));
}
}
return newSol;
}
private void mutate(Individual indiv) {
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
if (Math.random() <= mutationRate) {
byte gene = (byte) Math.round(Math.random());
indiv.setSingleGene(i, gene);
}
}
}
private Individual tournamentSelection(Population pop) {
Population tournament = new Population(tournamentSize, false);
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.getIndividuals().size());
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
}
Individual fittest = tournament.getFittest();
return fittest;
} | protected static int getFitness(Individual individual) {
int fitness = 0;
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
if (individual.getSingleGene(i) == solution[i]) {
fitness++;
}
}
return fitness;
}
protected int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
protected void setSolution(String newSolution) {
solution = new byte[newSolution.length()];
for (int i = 0; i < newSolution.length(); i++) {
String character = newSolution.substring(i, i + 1);
if (character.contains("0") || character.contains("1")) {
solution[i] = Byte.parseByte(character);
} else {
solution[i] = 0;
}
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\binary\SimpleGeneticAlgorithm.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.