instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event)
{
final MaterialEvent lightWeightEvent = materialEventConverter.toMaterialEvent(event);
try (final MDCCloseable ignored = MDC.putCloseable("MaterialEventClass", lightWeightEvent.getClass().getName()))
{
logger.debug("Received MaterialEvent={}", lightWeightEvent);
// make sure that every record we create has the correct AD_Client_ID and AD_Org_ID
final Properties temporaryCtx = Env.copyCtx(Env.getCtx());
Env.setClientId(temporaryCtx, lightWeightEvent.getClientId());
Env.setOrgId(temporaryCtx, lightWeightEvent.getOrgId());
if (lightWeightEvent.getUserId().isRegularUser())
{
Env.setLoggedUserId(temporaryCtx, lightWeightEvent.getUserId());
}
try (final IAutoCloseable ignored1 = Env.switchContext(temporaryCtx))
{
invokeListenerInTrx(lightWeightEvent);
}
}
}
private void invokeListenerInTrx(@NonNull final MaterialEvent materialEvent)
{
Services.get(ITrxManager.class).runInNewTrx(() -> materialEventHandlerRegistry.onEvent(materialEvent));
}
|
@Override
public String toString()
{
return MetasfreshEventBusService.class.getName() + ".internalListener";
}
};
public MetasfreshEventListener(
@NonNull final MaterialEventHandlerRegistry materialEventHandlerRegistry,
@NonNull final MetasfreshEventBusService metasfreshEventBusService,
@NonNull final MaterialEventConverter materialEventConverter)
{
this.materialEventConverter = materialEventConverter;
this.materialEventHandlerRegistry = materialEventHandlerRegistry;
this.metasfreshEventBusService = metasfreshEventBusService;
this.metasfreshEventBusService.subscribe(internalListener);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\eventbus\MetasfreshEventListener.java
| 1
|
请完成以下Java代码
|
public void initDefaultCommandConfig() {
if (defaultCommandConfig == null) {
defaultCommandConfig = new CommandConfig().setContextReusePossible(true);
}
}
@Override
public CommandInterceptor createTransactionInterceptor() {
if (transactionManager == null) {
throw new FlowableException("transactionManager is required property for SpringIdmEngineConfiguration, use " + StandaloneIdmEngineConfiguration.class.getName() + " otherwise");
}
return new SpringTransactionInterceptor(transactionManager);
}
@Override
public void initTransactionContextFactory() {
if (transactionContextFactory == null && transactionManager != null) {
transactionContextFactory = new SpringTransactionContextFactory(transactionManager, transactionSynchronizationAdapterOrder);
}
}
@Override
public IdmEngineConfiguration setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
return (IdmEngineConfiguration) super.setDataSource(dataSource);
} else {
|
// Wrap datasource in Transaction-aware proxy
DataSource proxiedDataSource = new TransactionAwareDataSourceProxy(dataSource);
return (IdmEngineConfiguration) super.setDataSource(proxiedDataSource);
}
}
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-spring\src\main\java\org\flowable\idm\spring\SpringIdmEngineConfiguration.java
| 1
|
请完成以下Java代码
|
public String getUsageHelp() {
return "[options] <password to encode>";
}
@Override
public Collection<HelpExample> getExamples() {
List<HelpExample> examples = new ArrayList<>();
examples.add(new HelpExample("To encode a password with the default (bcrypt) encoder",
"spring encodepassword mypassword"));
examples.add(new HelpExample("To encode a password with pbkdf2", "spring encodepassword -a pbkdf2 mypassword"));
return examples;
}
private static final class EncodePasswordOptionHandler extends OptionHandler {
@SuppressWarnings("NullAway.Init")
private OptionSpec<String> algorithm;
@Override
protected void options() {
this.algorithm = option(Arrays.asList("algorithm", "a"),
"The algorithm to use. Supported algorithms: "
+ StringUtils.collectionToDelimitedString(ENCODERS.keySet(), ", ")
+ ". The default algorithm uses bcrypt")
.withRequiredArg()
.defaultsTo("default");
}
@Override
protected ExitStatus run(OptionSet options) {
if (options.nonOptionArguments().size() != 1) {
Log.error("A single password option must be provided");
return ExitStatus.ERROR;
|
}
String algorithm = options.valueOf(this.algorithm);
String password = (String) options.nonOptionArguments().get(0);
Supplier<PasswordEncoder> encoder = ENCODERS.get(algorithm);
if (encoder == null) {
Log.error("Unknown algorithm, valid options are: "
+ StringUtils.collectionToCommaDelimitedString(ENCODERS.keySet()));
return ExitStatus.ERROR;
}
Log.info(encoder.get().encode(password));
return ExitStatus.OK;
}
}
}
|
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\encodepassword\EncodePasswordCommand.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ReceiverService {
/**
* 消费者实体对象
*/
private DefaultMQPushConsumer consumer;
/**
* 消费者组
*/
public static final String CONSUMER_GROUP = "test_consumer";
/**
* 通过构造函数 实例化对象
*/
public ReceiverService() throws MQClientException {
consumer = new DefaultMQPushConsumer(CONSUMER_GROUP);
consumer.setNamesrvAddr(JmsConfig.NAME_SERVER);
//消费模式:一个新的订阅组第一次启动从队列的最后位置开始消费 后续再启动接着上次消费的进度开始消费
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
//订阅主题和 标签( * 代表所有标签)下信息
consumer.subscribe(JmsConfig.TOPIC, "*");
// //注册消费的监听 并在此监听中消费信息,并返回消费的状态信息
consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
// msgs中只收集同一个topic,同一个tag,并且key相同的message
|
// 会把不同的消息分别放置到不同的队列中
try {
for (Message msg : msgs) {
//消费者获取消息 这里只输出 不做后面逻辑处理
String body = new String(msg.getBody(), "utf-8");
System.out.println(String.format("Consumer-获取消息-主题topic为={ %s }, 消费消息为={ %s }", msg.getTopic(), body));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
consumer.start();
System.out.println("消费者 启动成功=======");
}
}
|
repos\springBoot-master\springboot-rocketmq\src\main\java\cn\abel\queue\service\ReceiverService.java
| 2
|
请完成以下Java代码
|
public boolean isCompleted() {
return state == COMPLETED.getStateCode();
}
public boolean isTerminated() {
return state == TERMINATED.getStateCode();
}
public boolean isFailed() {
return state == FAILED.getStateCode();
}
public boolean isSuspended() {
return state == SUSPENDED.getStateCode();
}
public boolean isClosed() {
return state == CLOSED.getStateCode();
}
|
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[businessKey=" + businessKey
+ ", startUserId=" + createUserId
+ ", superCaseInstanceId=" + superCaseInstanceId
+ ", superProcessInstanceId=" + superProcessInstanceId
+ ", durationInMillis=" + durationInMillis
+ ", createTime=" + startTime
+ ", closeTime=" + endTime
+ ", id=" + id
+ ", eventType=" + eventType
+ ", caseExecutionId=" + caseExecutionId
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricCaseInstanceEventEntity.java
| 1
|
请完成以下Java代码
|
public class FireNForgetClient {
private static final Logger LOG = LoggerFactory.getLogger(FireNForgetClient.class);
private final RSocket socket;
private final List<Float> data;
public FireNForgetClient() {
this.socket = RSocketFactory.connect()
.transport(TcpClientTransport.create("localhost", TCP_PORT))
.start()
.block();
this.data = Collections.unmodifiableList(generateData());
}
/**
* Send binary velocity (float) every 50ms
*/
public void sendData() {
Flux.interval(Duration.ofMillis(50))
.take(data.size())
.map(this::createFloatPayload)
.flatMap(socket::fireAndForget)
.blockLast();
}
/**
* Create a binary payload containing a single float value
*
* @param index Index into the data list
* @return Payload ready to send to the server
*/
private Payload createFloatPayload(Long index) {
float velocity = data.get(index.intValue());
ByteBuffer buffer = ByteBuffer.allocate(4).putFloat(velocity);
|
buffer.rewind();
return DefaultPayload.create(buffer);
}
/**
* Generate sample data
*
* @return List of random floats
*/
private List<Float> generateData() {
List<Float> dataList = new ArrayList<>(DATA_LENGTH);
float velocity = 0;
for (int i = 0; i < DATA_LENGTH; i++) {
velocity += Math.random();
dataList.add(velocity);
}
return dataList;
}
/**
* Get the data used for this client.
*
* @return list of data values
*/
public List<Float> getData() {
return data;
}
public void dispose() {
this.socket.dispose();
}
}
|
repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\FireNForgetClient.java
| 1
|
请完成以下Java代码
|
public IReturnsInOutProducer setMovementType(final String movementType)
{
assertConfigurable();
_movementType = movementType;
return this;
}
@Override
public IReturnsInOutProducer setM_Warehouse(final I_M_Warehouse warehouse)
{
assertConfigurable();
_warehouse = warehouse;
return this;
}
private static I_C_DocType getEmptiesDocType(final String docBaseType, final int adClientId, final int adOrgId, final boolean isSOTrx)
{
//
// Search for specific empties shipment/receipt document sub-type (task 07694)
// 07694: using the empties-subtype for receipts.
final String docSubType = isSOTrx ? X_C_DocType.DOCSUBTYPE_Leergutanlieferung : X_C_DocType.DOCSUBTYPE_Leergutausgabe;
final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
final List<I_C_DocType> docTypes = docTypeDAO.retrieveDocTypesByBaseType(DocTypeQuery.builder()
.docBaseType(docBaseType)
.docSubType(DocTypeQuery.DOCSUBTYPE_Any)
.adClientId(adClientId)
.adOrgId(adOrgId)
.build());
if (docTypes == null)
{
logger.warn("No document types found for docBaseType={}, adClientId={}, adOrgId={}", docBaseType, adClientId, adOrgId);
return null;
}
for (final I_C_DocType docType : docTypes)
{
final String subType = docType.getDocSubType();
if (docSubType.equals(subType))
{
return docType;
}
}
//
// If the empties doc type was not found (should not happen) fallback to the default one
{
final I_C_DocType defaultDocType = docTypes.get(0);
logger.warn("No empties document type found for docBaseType={}, docSubType={}, adClientId={}, adOrgId={}. Using fallback docType={}", docBaseType, docSubType, adClientId, adOrgId, defaultDocType);
return defaultDocType;
}
}
@Override
protected void createLines()
{
inoutLinesBuilder.addSources(sources);
|
inoutLinesBuilder.create();
}
@Override
protected int getReturnsDocTypeId(final String docBaseType, final boolean isSOTrx, final int adClientId, final int adOrgId)
{
final I_C_DocType docType = getEmptiesDocType(docBaseType, adClientId, adOrgId, isSOTrx);
DocTypeId docTypeId = docType == null ? null : DocTypeId.ofRepoId(docType.getC_DocType_ID());
// If the empties doc type was not found (should not happen) fallback to the default one
if (docTypeId == null)
{
final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
docTypeId = docTypeDAO.getDocTypeId(
DocTypeQuery.builder()
.docBaseType(docBaseType)
.adClientId(adClientId)
.adOrgId(adOrgId)
.build()
//Env.getCtx(), docBaseType, adClientId, adOrgId, ITrx.TRXNAME_None
);
}
return DocTypeId.toRepoId(docTypeId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\impl\EmptiesInOutProducer.java
| 1
|
请完成以下Java代码
|
public HistoryLevel execute(CommandContext commandContext) {
if (processDefinitionId == null) {
throw new FlowableIllegalArgumentException("processDefinitionId is null");
}
HistoryLevel historyLevel = null;
ProcessDefinition processDefinition = CommandContextUtil.getProcessDefinitionEntityManager(commandContext).findById(processDefinitionId);
BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(processDefinitionId);
Process process = bpmnModel.getProcessById(processDefinition.getKey());
if (process.getExtensionElements().containsKey("historyLevel")) {
ExtensionElement historyLevelElement = process.getExtensionElements().get("historyLevel").iterator().next();
String historyLevelValue = historyLevelElement.getElementText();
|
if (StringUtils.isNotEmpty(historyLevelValue)) {
try {
historyLevel = HistoryLevel.getHistoryLevelForKey(historyLevelValue);
} catch (Exception e) {
}
}
}
if (historyLevel == null) {
historyLevel = CommandContextUtil.getProcessEngineConfiguration(commandContext).getHistoryLevel();
}
return historyLevel;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetProcessDefinitionHistoryLevelModelCmd.java
| 1
|
请完成以下Java代码
|
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Link.
@param Link
Contains URL to a target
*/
public void setLink (String Link)
{
set_Value (COLUMNNAME_Link, Link);
}
/** Get Link.
@return Contains URL to a target
*/
public String getLink ()
{
return (String)get_Value(COLUMNNAME_Link);
}
|
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsChannel.java
| 1
|
请完成以下Java代码
|
private static String extractSQLStateOrNull(final Throwable t)
{
final SQLException sqlException = extractSQLExceptionOrNull(t);
if (sqlException == null)
{
return null;
}
return sqlException.getSQLState();
}
/**
* Check if Unique Constraint Exception (aka ORA-00001)
*
* @param e exception
*/
public static boolean isUniqueContraintError(final Throwable e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_unique_violation);
}
//
return isErrorCode(e, 1);
}
/**
* Check if "integrity constraint (string.string) violated - child record found" exception (aka ORA-02292)
*/
public static boolean isChildRecordFoundError(final Exception e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_foreign_key_violation);
}
return isErrorCode(e, 2292);
}
public static boolean isForeignKeyViolation(final Throwable e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_foreign_key_violation);
}
// NOTE: on oracle there are many ORA-codes for foreign key violation
// below i am adding a few of them, but pls note that it's not tested at all
return isErrorCode(e, 2291) // integrity constraint (string.string) violated - parent key not found
|| isErrorCode(e, 2292) // integrity constraint (string.string) violated - child record found
|
//
;
}
/**
* Check if "invalid identifier" exception (aka ORA-00904)
*
* @param e exception
*/
public static boolean isInvalidIdentifierError(final Exception e)
{
return isErrorCode(e, 904);
}
/**
* Check if "invalid username/password" exception (aka ORA-01017)
*
* @param e exception
*/
public static boolean isInvalidUserPassError(final Exception e)
{
return isErrorCode(e, 1017);
}
/**
* Check if "time out" exception (aka ORA-01013)
*/
public static boolean isTimeout(final Exception e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_query_canceled);
}
return isErrorCode(e, 1013);
}
/**
* Task 08353
*/
public static boolean isDeadLockDetected(final Throwable e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_deadlock_detected);
}
return isErrorCode(e, 40001); // not tested for oracle, just did a brief googling
}
} // DBException
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\DBException.java
| 1
|
请完成以下Java代码
|
public ProcessInstanceBuilder createProcessInstanceBuilder() {
return new ProcessInstanceBuilderImpl(this);
}
@Override
public ChangeActivityStateBuilder createChangeActivityStateBuilder() {
return new ChangeActivityStateBuilderImpl(this);
}
@Override
public Execution addMultiInstanceExecution(String activityId, String parentExecutionId, Map<String, Object> executionVariables) {
return commandExecutor.execute(new AddMultiInstanceExecutionCmd(activityId, parentExecutionId, executionVariables));
}
@Override
public void deleteMultiInstanceExecution(String executionId, boolean executionIsCompleted) {
commandExecutor.execute(new DeleteMultiInstanceExecutionCmd(executionId, executionIsCompleted));
}
public ProcessInstance startProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.getProcessDefinitionId() != null || processInstanceBuilder.getProcessDefinitionKey() != null) {
return commandExecutor.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder));
} else if (processInstanceBuilder.getMessageName() != null) {
return commandExecutor.execute(new StartProcessInstanceByMessageCmd(processInstanceBuilder));
} else {
throw new FlowableIllegalArgumentException("No processDefinitionId, processDefinitionKey nor messageName provided");
}
}
public ProcessInstance startProcessInstanceAsync(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.getProcessDefinitionId() != null || processInstanceBuilder.getProcessDefinitionKey() != null) {
return (ProcessInstance) commandExecutor.execute(new StartProcessInstanceAsyncCmd(processInstanceBuilder));
} else {
throw new FlowableIllegalArgumentException("No processDefinitionId, processDefinitionKey provided");
}
}
|
public EventSubscription registerProcessInstanceStartEventSubscription(ProcessInstanceStartEventSubscriptionBuilderImpl builder) {
return commandExecutor.execute(new RegisterProcessInstanceStartEventSubscriptionCmd(builder));
}
public void migrateProcessInstanceStartEventSubscriptionsToProcessDefinitionVersion(ProcessInstanceStartEventSubscriptionModificationBuilderImpl builder) {
commandExecutor.execute(new ModifyProcessInstanceStartEventSubscriptionCmd(builder));
}
public void deleteProcessInstanceStartEventSubscriptions(ProcessInstanceStartEventSubscriptionDeletionBuilderImpl builder) {
commandExecutor.execute(new DeleteProcessInstanceStartEventSubscriptionCmd(builder));
}
public void changeActivityState(ChangeActivityStateBuilderImpl changeActivityStateBuilder) {
commandExecutor.execute(new ChangeActivityStateCmd(changeActivityStateBuilder));
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\RuntimeServiceImpl.java
| 1
|
请完成以下Java代码
|
public class LockExternalTaskCmd extends HandleExternalTaskCmd {
protected long lockDuration;
public LockExternalTaskCmd(String externalTaskId, String workerId, long lockDuration) {
super(externalTaskId, workerId);
this.lockDuration = lockDuration;
}
@Override
protected void execute(ExternalTaskEntity externalTask) {
externalTask.lock(workerId, lockDuration);
}
@Override
public String getErrorMessageOnWrongWorkerAccess() {
return "External Task " + externalTaskId + " cannot be locked by worker '" + workerId;
}
/*
Report a worker violation only if another worker has locked the task,
and the lock expiration time is still not expired.
*/
@Override
protected boolean validateWorkerViolation(ExternalTaskEntity externalTask) {
String existingWorkerId = externalTask.getWorkerId();
Date existingLockExpirationTime = externalTask.getLockExpirationTime();
|
// check if another worker is attempting to lock the same task
boolean workerValidation = existingWorkerId != null && !workerId.equals(existingWorkerId);
// and check if an existing lock is already expired
boolean lockValidation = existingLockExpirationTime != null
&& !ClockUtil.getCurrentTime().after(existingLockExpirationTime);
return workerValidation && lockValidation;
}
@Override
protected void validateInput() {
super.validateInput();
EnsureUtil.ensurePositive(BadUserRequestException.class, "lockDuration", lockDuration);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\LockExternalTaskCmd.java
| 1
|
请完成以下Java代码
|
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public org.compiere.model.I_S_Resource getS_Resource()
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
|
}
@Override
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions_v.java
| 1
|
请完成以下Java代码
|
public class SentinelConStants {
public static final String GROUP_ID = "SENTINEL_GROUP";
/**
* 流控规则
*/
public static final String FLOW_DATA_ID_POSTFIX = "-flow-rules";
/**
* 热点参数
*/
public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-rules";
/**
* 降级规则
*/
public static final String DEGRADE_DATA_ID_POSTFIX = "-degrade-rules";
/**
* 系统规则
*/
|
public static final String SYSTEM_DATA_ID_POSTFIX = "-system-rules";
/**
* 授权规则
*/
public static final String AUTHORITY_DATA_ID_POSTFIX = "-authority-rules";
/**
* 网关API
*/
public static final String GETEWAY_API_DATA_ID_POSTFIX = "-api-rules";
/**
* 网关流控规则
*/
public static final String GETEWAY_FLOW_DATA_ID_POSTFIX = "-flow-rules";
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\constants\SentinelConStants.java
| 1
|
请完成以下Java代码
|
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public MachineInfo toMachineInfo() {
MachineInfo machineInfo = new MachineInfo();
machineInfo.setApp(app);
machineInfo.setHostname(hostname);
machineInfo.setIp(ip);
|
machineInfo.setPort(port);
machineInfo.setLastHeartbeat(timestamp.getTime());
machineInfo.setHeartbeatVersion(timestamp.getTime());
return machineInfo;
}
@Override
public String toString() {
return "MachineEntity{" +
"id=" + id +
", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", app='" + app + '\'' +
", ip='" + ip + '\'' +
", hostname='" + hostname + '\'' +
", timestamp=" + timestamp +
", port=" + port +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MachineEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringBootSpinProcessEnginePlugin extends SpinProcessEnginePlugin {
@Autowired
protected Optional<CamundaJacksonFormatConfiguratorJSR310> dataFormatConfiguratorJsr310;
@Autowired
protected Optional<CamundaJacksonFormatConfiguratorParameterNames> dataFormatConfiguratorParameterNames;
@Autowired
protected Optional<CamundaJacksonFormatConfiguratorJdk8> dataFormatConfiguratorJdk8;
@Override
public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
ClassLoader classloader = ClassLoaderUtil.getClassloader(SpringBootSpinProcessEnginePlugin.class);
loadSpringBootDataFormats(classloader);
|
}
protected void loadSpringBootDataFormats(ClassLoader classloader) {
List<DataFormatConfigurator> configurators = new ArrayList<>();
// add the auto-config Jackson Java 8 module configurators
dataFormatConfiguratorJsr310.ifPresent(configurator -> configurators.add(configurator));
dataFormatConfiguratorParameterNames.ifPresent(configurator -> configurators.add(configurator));
dataFormatConfiguratorJdk8.ifPresent(configurator -> configurators.add(configurator));
// next, add any configurators defined in the spring.factories file
configurators.addAll(SpringFactoriesLoader.loadFactories(DataFormatConfigurator.class, classloader));
DataFormats.loadDataFormats(classloader, configurators);
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\spin\SpringBootSpinProcessEnginePlugin.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Boolean getHasChildren() {
return subCount > 0;
}
@ApiModelProperty(value = "是否叶子节点")
public Boolean getLeaf() {
return subCount <= 0;
}
@ApiModelProperty(value = "标题")
public String getLabel() {
return title;
}
@Override
public boolean equals(Object o) {
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MenuDto menuDto = (MenuDto) o;
return Objects.equals(id, menuDto.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\dto\MenuDto.java
| 2
|
请完成以下Java代码
|
public class ProductDocument implements Serializable {
@Id
private String id;
//@Field(analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String productName;
//@Field(analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String productDesc;
private Date createTime;
private Date updateTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
|
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\document\ProductDocument.java
| 1
|
请完成以下Java代码
|
public void setField(final GridField mField)
{
// To determine behavior
m_GridField = mField;
m_mField = mField;
// if (m_mField != null)
// FieldRecordInfo.addMenu(this, popupMenu);
//
// (re)Initialize our attribute context because we want to make sure
// it is using exactly the same context as the GridField it is using when it's exporting the values to context.
// If we are not doing this it might be (in some cases) that different contexts are used
// (e.g. process parameters panel, when using Product Attribute field won't find the M_Product_ID because it's in a different context instance)
// For more info, see 08723.
if (mField != null)
{
attributeContext = VPAttributeWindowContext.of(mField);
}
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField()
{
return m_mField;
}
private String getTableName()
{
final GridField gridField = getField();
return gridField == null ? null : gridField.getTableName();
}
private int getAD_Column_ID()
{
final GridField gridField = getField();
return gridField == null ? -1 : gridField.getAD_Column_ID();
}
@Override
public void addActionListener(final ActionListener listener)
{
} // addActionListener
@Override
public void actionPerformed(final ActionEvent e)
{
try
{
if (e.getSource() == m_button)
{
actionButton();
}
}
catch (final Exception ex)
{
Services.get(IClientUI.class).error(attributeContext.getWindowNo(), ex);
}
} // actionPerformed
private void actionButton()
{
if (!m_button.isEnabled())
|
{
return;
}
throw new UnsupportedOperationException();
}
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
final String propertyName = evt.getPropertyName();
if (propertyName.equals(org.compiere.model.GridField.PROPERTY))
{
setValue(evt.getNewValue());
}
else if (propertyName.equals(org.compiere.model.GridField.REQUEST_FOCUS))
{
requestFocus();
}
}
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public void addMouseListener(final MouseListener l)
{
m_text.addMouseListener(l);
}
} // VPAttribute
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPAttribute.java
| 1
|
请完成以下Java代码
|
public int getM_CostElement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_InOut getM_InOut() throws RuntimeException
{
return (I_M_InOut)MTable.get(getCtx(), I_M_InOut.Table_Name)
.getPO(getM_InOut_ID(), get_TrxName()); }
/** Set Shipment/Receipt.
@param M_InOut_ID
Material Shipment Document
*/
public void setM_InOut_ID (int M_InOut_ID)
{
if (M_InOut_ID < 1)
set_Value (COLUMNNAME_M_InOut_ID, null);
else
set_Value (COLUMNNAME_M_InOut_ID, Integer.valueOf(M_InOut_ID));
}
/** Get Shipment/Receipt.
@return Material Shipment Document
*/
public int getM_InOut_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOut_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_InOutLine getM_InOutLine() throws RuntimeException
{
return (I_M_InOutLine)MTable.get(getCtx(), I_M_InOutLine.Table_Name)
.getPO(getM_InOutLine_ID(), get_TrxName()); }
/** Set Shipment/Receipt Line.
@param M_InOutLine_ID
Line on Shipment or Receipt document
*/
public void setM_InOutLine_ID (int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID));
}
/** Get Shipment/Receipt Line.
@return Line on Shipment or Receipt document
*/
public int getM_InOutLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID);
if (ii == null)
|
return 0;
return ii.intValue();
}
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 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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_LandedCost.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
MessagingAdviceRSocketMessageHandlerCustomizer messagingAdviceRSocketMessageHandlerCustomizer(
ApplicationContext applicationContext) {
return new MessagingAdviceRSocketMessageHandlerCustomizer(applicationContext);
}
}
static final class MessagingAdviceRSocketMessageHandlerCustomizer implements RSocketMessageHandlerCustomizer {
private final ApplicationContext applicationContext;
MessagingAdviceRSocketMessageHandlerCustomizer(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void customize(RSocketMessageHandler messageHandler) {
ControllerAdviceBean.findAnnotatedBeans(this.applicationContext)
.forEach((controllerAdviceBean) -> messageHandler
.registerMessagingAdvice(new ControllerAdviceBeanWrapper(controllerAdviceBean)));
}
}
private static final class ControllerAdviceBeanWrapper implements MessagingAdviceBean {
private final ControllerAdviceBean adviceBean;
|
private ControllerAdviceBeanWrapper(ControllerAdviceBean adviceBean) {
this.adviceBean = adviceBean;
}
@Override
public @Nullable Class<?> getBeanType() {
return this.adviceBean.getBeanType();
}
@Override
public Object resolveBean() {
return this.adviceBean.resolveBean();
}
@Override
public boolean isApplicableToBeanType(Class<?> beanType) {
return this.adviceBean.isApplicableToBeanType(beanType);
}
@Override
public int getOrder() {
return this.adviceBean.getOrder();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketMessagingAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Product {
@Id
@GeneratedValue
private Long _id;
private String description;
private BigDecimal price;
private String imageUrl;
public Long getId() {
return _id;
}
public void setId(Long id) {
this._id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
|
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
|
repos\SpringBootVulExploit-master\repository\springboot-mysql-jdbc-rce\src\main\java\code\landgrey\domain\Product.java
| 2
|
请完成以下Java代码
|
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getSourceExpression() {
return sourceExpression;
}
public void setSourceExpression(String sourceExpression) {
this.sourceExpression = sourceExpression;
}
public String getTargetExpression() {
return targetExpression;
}
public void setTargetExpression(String targetExpression) {
this.targetExpression = targetExpression;
}
public boolean isTransient() {
return isTransient;
}
|
public void setTransient(boolean isTransient) {
this.isTransient = isTransient;
}
@Override
public IOParameter clone() {
IOParameter clone = new IOParameter();
clone.setValues(this);
return clone;
}
public void setValues(IOParameter otherElement) {
super.setValues(otherElement);
setSource(otherElement.getSource());
setSourceExpression(otherElement.getSourceExpression());
setTarget(otherElement.getTarget());
setTargetExpression(otherElement.getTargetExpression());
setTransient(otherElement.isTransient());
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\IOParameter.java
| 1
|
请完成以下Java代码
|
public static <T> IQueryFilter<T> getInstance(final Class<T> clazz)
{
return getInstance();
}
@SuppressWarnings("rawtypes")
private static final ActiveRecordQueryFilter instance = new ActiveRecordQueryFilter();
private static final String COLUMNNAME_IsActive = "IsActive";
private final String sql;
private final List<Object> sqlParams;
private ActiveRecordQueryFilter()
{
this.sql = COLUMNNAME_IsActive + "=?";
this.sqlParams = Arrays.asList((Object)true);
}
@Override
public String toString()
{
return "Active";
}
@Override
public String getSql()
{
return sql;
|
}
@Override
public List<Object> getSqlParams(final Properties ctx)
{
return sqlParams;
}
@Override
public boolean accept(final T model)
{
final Object isActiveObj = InterfaceWrapperHelper.getValueOrNull(model, COLUMNNAME_IsActive);
final boolean isActive = DisplayType.toBoolean(isActiveObj);
return isActive;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ActiveRecordQueryFilter.java
| 1
|
请完成以下Java代码
|
public void setVisited (boolean visited)
{
m_visited = visited;
if (m_visited)
{
setBackground(Color.green);
}
else
{
setBackground(Color.lightGray);
}
} // setVisited
/**
* Get Selected
* @return selected
*/
public boolean isSelected()
{
return m_selected;
} // isSelected
/**
* Get Client ID
* @return Client ID
*/
public int getAD_Client_ID()
{
return m_node.getClientId().getRepoId();
} // getAD_Client_ID
/**
* Is the node Editable
* @return yes if the Client is the same
*/
public boolean isEditable()
{
return getAD_Client_ID() == Env.getAD_Client_ID(Env.getCtx());
} // isEditable
public WFNodeId getNodeId()
{
return m_node.getId();
}
public WorkflowNodeModel getModel()
{
return m_node;
} // getModel
/**
* Set Location - also for Node.
* @param x x
* @param y y
*/
public void setLocation (int x, int y)
{
super.setLocation (x, y);
m_node.setXPosition(x);
m_node.setYPosition(y);
}
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("WFNode[");
sb.append(getNodeId().getRepoId()).append("-").append(m_name)
.append(",").append(getBounds())
|
.append("]");
return sb.toString();
} // toString
/**
* Get Font.
* Italics if not editable
* @return font
*/
public Font getFont ()
{
Font base = new Font(null);
if (!isEditable())
return base;
// Return Bold Italic Font
return new Font(base.getName(), Font.ITALIC | Font.BOLD, base.getSize());
} // getFont
/**************************************************************************
* Get Preferred Size
* @return size
*/
public Dimension getPreferredSize ()
{
return s_size;
} // getPreferredSize
/**
* Paint Component
* @param g Graphics
*/
protected void paintComponent (Graphics g)
{
Graphics2D g2D = (Graphics2D)g;
// center icon
m_icon.paintIcon(this, g2D, s_size.width/2 - m_icon.getIconWidth()/2, 5);
// Paint Text
Color color = getForeground();
g2D.setPaint(color);
Font font = getFont();
//
AttributedString aString = new AttributedString(m_name);
aString.addAttribute(TextAttribute.FONT, font);
aString.addAttribute(TextAttribute.FOREGROUND, color);
AttributedCharacterIterator iter = aString.getIterator();
//
LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext());
float width = s_size.width - m_icon.getIconWidth() - 2;
TextLayout layout = measurer.nextLayout(width);
// center text
float xPos = (float)(s_size.width/2 - layout.getBounds().getWidth()/2);
float yPos = m_icon.getIconHeight() + 20;
//
layout.draw(g2D, xPos, yPos);
width = s_size.width - 4; // 2 pt
while (measurer.getPosition() < iter.getEndIndex())
{
layout = measurer.nextLayout(width);
yPos += layout.getAscent() + layout.getDescent() + layout.getLeading();
layout.draw(g2D, xPos, yPos);
}
} // paintComponent
} // WFNode
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFNodeComponent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/info", "/actuator/info");
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentTypeStrategy(new CommandLineContentNegotiationStrategy());
}
/**
* A command-line aware {@link ContentNegotiationStrategy} that forces the media type
* to "text/plain" for compatible agents.
*/
private static final class CommandLineContentNegotiationStrategy implements ContentNegotiationStrategy {
private final UrlPathHelper urlPathHelper = new UrlPathHelper();
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request) {
String path = this.urlPathHelper
.getPathWithinApplication(request.getNativeRequest(HttpServletRequest.class));
if (!StringUtils.hasText(path) || !path.equals("/")) { // Only care about "/"
|
return MEDIA_TYPE_ALL_LIST;
}
String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
if (userAgent != null) {
Agent agent = Agent.fromUserAgent(userAgent);
if (agent != null) {
if (AgentId.CURL.equals(agent.getId()) || AgentId.HTTPIE.equals(agent.getId())) {
return Collections.singletonList(MediaType.TEXT_PLAIN);
}
}
}
return Collections.singletonList(MediaType.APPLICATION_JSON);
}
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\autoconfigure\InitializrWebConfig.java
| 2
|
请完成以下Java代码
|
public class UserDO implements Serializable {
/**
* 用户编号
*/
private Integer id;
/**
* 账号
*/
private String username;
/**
* 密码(明文)
*
* ps:生产环境下,千万不要明文噢
*/
private String password;
/**
* 创建时间
*/
private Date createTime;
/**
* 是否删除
*/
@TableLogic
private Integer deleted;
public Integer getId() {
return id;
}
public UserDO setId(Integer id) {
this.id = id;
return this;
}
public String getUsername() {
return username;
}
public UserDO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public UserDO setPassword(String password) {
this.password = password;
return this;
}
|
public Date getCreateTime() {
return createTime;
}
public UserDO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
public Integer getDeleted() {
return deleted;
}
public UserDO setDeleted(Integer deleted) {
this.deleted = deleted;
return this;
}
@Override
public String toString() {
return "UserDO{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", createTime=" + createTime +
", deleted=" + deleted +
'}';
}
}
|
repos\SpringBoot-Labs-master\lab-21\lab-21-cache-redis\src\main\java\cn\iocoder\springboot\lab21\cache\dataobject\UserDO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public UserVO get2(@PathVariable("id") Integer id) {
return userService.get(id);
}
/**
* 添加用户
*
* @param addDTO 添加用户信息 DTO
* @return 添加成功的用户编号
*/
@PostMapping("")
public Integer add(UserAddDTO addDTO) {
// 插入用户记录,返回编号
Integer returnId = 1;
// 返回用户编号
return returnId;
}
/**
* 更新指定用户编号的用户
*
* @param id 用户编号
* @param updateDTO 更新用户信息 DTO
* @return 是否修改成功
*/
@PutMapping("/{id}")
public Boolean update(@PathVariable("id") Integer id, UserUpdateDTO updateDTO) {
// 将 id 设置到 updateDTO 中
|
updateDTO.setId(id);
// 更新用户记录
Boolean success = true;
// 返回更新是否成功
return success;
}
/**
* 删除指定用户编号的用户
*
* @param id 用户编号
* @return 是否删除成功
*/
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable("id") Integer id) {
// 删除用户记录
Boolean success = false;
// 返回是否更新成功
return success;
}
}
|
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-01\src\main\java\cn\iocoder\springboot\lab23\springmvc\controller\UserController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonShipmentOptions
{
@JsonProperty("ServiceLevel")
String serviceLevel;
@JsonProperty("TrackingURL")
@JsonSerialize(converter = BooleanToIntConverter.class)
Boolean trackingURL;
@JsonProperty("RequiredDeliveryDate")
String requiredDeliveryDate; // Expects DATETIME format, e.g., "YYYY-MM-DDTHH:mm:ss"
@JsonProperty("Visibility")
String visibility;
@JsonProperty("Submit")
@JsonSerialize(converter = BooleanToIntConverter.class)
Boolean submit;
@JsonProperty("Labels")
JsonLabelType labelType;
@JsonProperty("TicketUserName")
String ticketUserName;
|
@JsonProperty("WorkstationID")
UUID workstationID;
@JsonProperty("DropZoneLabelPrinterKey")
String dropZoneLabelPrinterKey;
@JsonProperty("DropZoneDocPrinterKey")
String dropZoneDocPrinterKey;
@JsonProperty("ValidatePostCode")
@JsonSerialize(converter = BooleanToIntConverter.class)
Boolean validatePostCode;
@JsonProperty("Place")
String place;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\json\JsonShipmentOptions.java
| 2
|
请完成以下Java代码
|
public IncidentQuery orderByProcessInstanceId() {
orderBy(IncidentQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
public IncidentQuery orderByProcessDefinitionId() {
orderBy(IncidentQueryProperty.PROCESS_DEFINITION_ID);
return this;
}
public IncidentQuery orderByCauseIncidentId() {
orderBy(IncidentQueryProperty.CAUSE_INCIDENT_ID);
return this;
}
public IncidentQuery orderByRootCauseIncidentId() {
orderBy(IncidentQueryProperty.ROOT_CAUSE_INCIDENT_ID);
return this;
}
public IncidentQuery orderByConfiguration() {
orderBy(IncidentQueryProperty.CONFIGURATION);
return this;
}
public IncidentQuery orderByTenantId() {
return orderBy(IncidentQueryProperty.TENANT_ID);
}
|
@Override
public IncidentQuery orderByIncidentMessage() {
return orderBy(IncidentQueryProperty.INCIDENT_MESSAGE);
}
//results ////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentCountByQueryCriteria(this);
}
@Override
public List<Incident> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentByQueryCriteria(this, page);
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IncidentQueryImpl.java
| 1
|
请完成以下Java代码
|
public Object getValue(ELContext context, Object base, Object property) {
if (base == null) {
String variable = (String) property; // according to javadoc, can only be a String
if ((EXECUTION_KEY.equals(property) && variableScope instanceof ExecutionEntity)
|| (TASK_KEY.equals(property) && variableScope instanceof TaskEntity)) {
context.setPropertyResolved(true);
return variableScope;
} else if (EXECUTION_KEY.equals(property) && variableScope instanceof TaskEntity) {
context.setPropertyResolved(true);
return ((TaskEntity) variableScope).getExecution();
} else if (LOGGED_IN_USER_KEY.equals(property)) {
context.setPropertyResolved(true);
return Authentication.getAuthenticatedUserId();
} else {
if (variableScope.hasVariable(variable)) {
context.setPropertyResolved(true); // if not set, the next elResolver in the CompositeElResolver will be called
return variableScope.getVariable(variable);
}
}
}
// property resolution (eg. bean.value) will be done by the BeanElResolver (part of the CompositeElResolver)
// It will use the bean resolved in this resolver as base.
return null;
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
if (base == null) {
String variable = (String) property;
return !variableScope.hasVariable(variable);
|
}
return true;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
if (base == null) {
String variable = (String) property;
if (variableScope.hasVariable(variable)) {
variableScope.setVariable(variable, value);
}
}
}
@Override
public Class<?> getCommonPropertyType(ELContext arg0, Object arg1) {
return Object.class;
}
@Override
public Class<?> getType(ELContext arg0, Object arg1, Object arg2) {
return Object.class;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\el\VariableScopeElResolver.java
| 1
|
请完成以下Java代码
|
private void cleanupEvents(long eventExpTime, boolean debug) {
for (EventType eventType : EventType.values()) {
if (eventType.isDebug() == debug) {
cleanupPartitions(eventType, eventExpTime);
}
}
}
private void cleanupPartitions(EventType eventType, long eventExpTime) {
partitioningRepository.dropPartitionsBefore(eventType.getTable(), eventExpTime, partitionConfiguration.getPartitionSizeInMs(eventType));
}
private void cleanupPartitionsCache(long expTime, boolean isDebug) {
for (EventType eventType : EventType.values()) {
if (eventType.isDebug() == isDebug) {
partitioningRepository.cleanupPartitionsCache(eventType.getTable(), expTime, partitionConfiguration.getPartitionSizeInMs(eventType));
}
}
}
private void parseUUID(String src, String paramName) {
if (!StringUtils.isEmpty(src)) {
|
try {
UUID.fromString(src);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Failed to convert " + paramName + " to UUID!");
}
}
}
private EventRepository<? extends EventEntity<?>, ?> getEventRepository(EventType eventType) {
var repository = repositories.get(eventType);
if (repository == null) {
throw new RuntimeException("Event type: " + eventType + " is not supported!");
}
return repository;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\event\JpaBaseEventDao.java
| 1
|
请完成以下Java代码
|
public int getDD_OrderLine_Alternative_ID()
{
return get_ValueAsInt(COLUMNNAME_DD_OrderLine_Alternative_ID);
}
@Override
public org.eevolution.model.I_DD_OrderLine getDD_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class);
}
@Override
public void setDD_OrderLine(final org.eevolution.model.I_DD_OrderLine DD_OrderLine)
{
set_ValueFromPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class, DD_OrderLine);
}
@Override
public void setDD_OrderLine_ID (final int DD_OrderLine_ID)
{
if (DD_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_DD_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DD_OrderLine_ID, DD_OrderLine_ID);
}
@Override
public int getDD_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_DD_OrderLine_ID);
}
@Override
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class);
}
@Override
public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance);
}
@Override
public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyDelivered (final BigDecimal QtyDelivered)
{
set_Value (COLUMNNAME_QtyDelivered, QtyDelivered);
}
@Override
public BigDecimal getQtyDelivered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDelivered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInTransit (final BigDecimal QtyInTransit)
{
set_Value (COLUMNNAME_QtyInTransit, QtyInTransit);
}
@Override
public BigDecimal getQtyInTransit()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInTransit);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_OrderLine_Alternative.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
private <T> void registerBeans(String location, String pattern, Class<T> type,
Function<Resource, T> beanSupplier, BeanDefinitionRegistry registry) {
for (Resource resource : getResources(location, pattern)) {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(type, () -> beanSupplier.apply(resource))
.getBeanDefinition();
String filename = resource.getFilename();
Assert.state(filename != null, "'filename' must not be null");
registry.registerBeanDefinition(StringUtils.stripFilenameExtension(filename), beanDefinition);
}
}
private Resource[] getResources(String location, String pattern) {
|
try {
return this.applicationContext.getResources(ensureTrailingSlash(location) + pattern);
}
catch (IOException ex) {
return new Resource[0];
}
}
private String ensureTrailingSlash(String path) {
return path.endsWith("/") ? path : path + "/";
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\autoconfigure\WebServicesAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BookstoreService {
private final TransactionTemplate template;
private final BookRepository bookRepository;
public BookstoreService(BookRepository bookRepository, TransactionTemplate template) {
this.bookRepository = bookRepository;
this.template = template;
}
public void fetchBooksViaTwoTransactions() {
template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
List<Book> books = bookRepository
|
.findTop3ByStatus(BookStatus.PENDING, Sort.by(Sort.Direction.ASC, "id"));
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
List<Book> books = bookRepository
.findTop3ByStatus(BookStatus.PENDING, Sort.by(Sort.Direction.ASC, "id"));
System.out.println("Second transaction: " + books);
}
});
System.out.println("First transaction: " + books);
}
});
System.out.println("Done!");
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootMySqlSkipLocked\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public static void dumpAllLevelsUpToRoot(final String loggerName)
{
final Logger logger = getLogger(loggerName);
if (logger == null)
{
return;
}
dumpAllLevelsUpToRoot(logger);
}
/**
* @see #dumpAllLevelsUpToRoot(Logger)
*/
public static void dumpAllLevelsUpToRoot(final Class<?> clazz)
{
final Logger logger = getLogger(clazz);
if (logger == null)
{
return;
}
dumpAllLevelsUpToRoot(logger);
}
/**
* Helper method to print (on System.out) all log levels starting from given logger, up to the root.
* <p>
* This method is useful in case you are debugging why a given logger does not have the correct effective level.
*/
public static void dumpAllLevelsUpToRoot(final Logger logger)
{
final Consumer<Logger> dumpLevel = (currentLogger) -> {
final String currentLoggerInfo;
if (currentLogger instanceof ch.qos.logback.classic.Logger)
{
final ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger)currentLogger;
currentLoggerInfo = "effectiveLevel=" + logbackLogger.getEffectiveLevel() + ", level=" + logbackLogger.getLevel();
}
else
{
currentLoggerInfo = "unknown level for logger object " + currentLogger + " (" + currentLogger.getClass() + ")";
}
System.out.println(" * " + currentLogger.getName() + "(" + System.identityHashCode(currentLogger) + "): " + currentLoggerInfo);
};
System.out.println("\nDumping all log levels starting from " + logger);
|
forAllLevelsUpToRoot(logger, dumpLevel);
}
public static void forAllLevelsUpToRoot(final Logger logger, final Consumer<Logger> consumer)
{
Logger currentLogger = logger;
String currentLoggerName = currentLogger.getName();
while (currentLogger != null)
{
consumer.accept(currentLogger);
final int idx = currentLoggerName.lastIndexOf(".");
if (idx < 0)
{
break;
}
currentLoggerName = currentLoggerName.substring(0, idx);
currentLogger = getLogger(currentLoggerName);
}
consumer.accept(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME));
}
private LogManager()
{
super();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\LogManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserController {
private Logger log = LoggerFactory.getLogger(this.getClass());
@GetMapping("/{id:\\d+}")
public User get(@PathVariable Long id) {
log.info("获取用户id为 " + id + "的信息");
return new User(id, "mrbird", "123456");
}
@GetMapping("users")
public List<User> get(String ids) {
log.info("批量获取用户信息");
List<User> list = new ArrayList<>();
for (String id : ids.split(",")) {
list.add(new User(Long.valueOf(id), "user" + id, "123456"));
}
return list;
}
@GetMapping
public List<User> get() {
List<User> list = new ArrayList<>();
list.add(new User(1L, "mrbird", "123456"));
list.add(new User(2L, "scott", "123456"));
log.info("获取用户信息 " + list);
return list;
}
|
@PostMapping
public void add(@RequestBody User user) {
log.info("新增用户成功 " + user);
}
@PutMapping
public void update(@RequestBody User user) {
log.info("更新用户成功 " + user);
}
@DeleteMapping("/{id:\\d+}")
public void delete(@PathVariable Long id) {
log.info("删除用户成功 " + id);
}
}
|
repos\SpringAll-master\30.Spring-Cloud-Hystrix-Circuit-Breaker\Eureka-Client\src\main\java\com\example\demo\controller\UserController.java
| 2
|
请完成以下Java代码
|
public final class JSONASILayout implements Serializable
{
public static JSONASILayout of(final ASILayout layout, final JSONDocumentLayoutOptions options)
{
return new JSONASILayout(layout, options);
}
@JsonProperty("id")
private final String id;
@JsonProperty("caption")
private final String caption;
@JsonProperty("description")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final String description;
@JsonProperty("elements")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final List<JSONDocumentLayoutElement> elements;
private JSONASILayout(final ASILayout layout, final JSONDocumentLayoutOptions options)
{
final String adLanguage = options.getAdLanguage();
final DocumentId asiDescriptorId = layout.getASIDescriptorId();
this.id = asiDescriptorId == null ? null : asiDescriptorId.toJson();
caption = layout.getCaption(adLanguage);
description = layout.getDescription(adLanguage);
elements = JSONDocumentLayoutElement.ofList(layout.getElements(), options);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
|
.omitNullValues()
.add("id", id)
.add("caption", caption)
.add("description", description)
.add("elements", elements)
.toString();
}
public String getCaption()
{
return caption;
}
public String getDescription()
{
return description;
}
public List<JSONDocumentLayoutElement> getElements()
{
return elements;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\json\JSONASILayout.java
| 1
|
请完成以下Java代码
|
public void setC_BankStatementMatcher_ID (int C_BankStatementMatcher_ID)
{
if (C_BankStatementMatcher_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BankStatementMatcher_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BankStatementMatcher_ID, Integer.valueOf(C_BankStatementMatcher_ID));
}
/** Get Bank Statement Matcher.
@return Algorithm to match Bank Statement Info to Business Partners, Invoices and Payments
*/
public int getC_BankStatementMatcher_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementMatcher_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
|
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set 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.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementMatcher.java
| 1
|
请完成以下Java代码
|
public class DeadLetterJobEntityManager extends AbstractManager {
public DeadLetterJobEntity findJobById(String jobId) {
return (DeadLetterJobEntity) getDbSqlSession().selectOne("selectDeadLetterJob", jobId);
}
@SuppressWarnings("unchecked")
public List<DeadLetterJobEntity> findDeadLetterJobsByDuedate(Date duedate, Page page) {
final String query = "selectDeadLetterJobsByDuedate";
return getDbSqlSession().selectList(query, duedate, page);
}
@SuppressWarnings("unchecked")
public List<DeadLetterJobEntity> findDeadLetterJobsByExecutionId(String executionId) {
return getDbSqlSession().selectList("selectDeadLetterJobsByExecutionId", executionId);
}
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) {
final String query = "selectDeadLetterJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionKeyNoTenantId(String jobHandlerType, String processDefinitionKey) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionKeyNoTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionKeyAndTenantId(String jobHandlerType, String processDefinitionKey, String tenantId) {
Map<String, String> params = new HashMap<>(3);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
params.put("tenantId", tenantId);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionKeyAndTenantId", params);
|
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionId(String jobHandlerType, String processDefinitionId) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionId", processDefinitionId);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionId", params);
}
public long findDeadLetterJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectDeadLetterJobCountByQueryCriteria", jobQuery);
}
public void updateDeadLetterJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateDeadLetterJobTenantIdForDeployment", params);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeadLetterJobEntityManager.java
| 1
|
请完成以下Java代码
|
static String normalizeUploadFilename(final String name, final String contentType)
{
final String fileExtension = MimeType.getExtensionByType(contentType);
final String nameNormalized;
if (Check.isEmpty(name, true)
|| "blob".equals(name) // HARDCODED: this happens when the image is taken from webcam
)
{
nameNormalized = DATE_FORMAT.format(SystemTime.asZonedDateTime());
}
else
{
nameNormalized = name.trim();
}
return FileUtil.changeFileExtension(nameNormalized, fileExtension);
}
|
public WebuiImage getWebuiImage(@NonNull final WebuiImageId imageId, final int maxWidth, final int maxHeight)
{
final AdImage adImage = adImageRepository.getById(imageId.toAdImageId());
return WebuiImage.of(adImage, maxWidth, maxHeight);
}
public ResponseEntity<byte[]> getEmptyImage()
{
return ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.IMAGE_PNG)
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"\"")
.body(BaseEncoding.base64().decode(EMPTY_PNG_BASE64));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\WebuiImageService.java
| 1
|
请完成以下Java代码
|
public class EndEventXMLConverter extends BaseBpmnXMLConverter {
@Override
public Class<? extends BaseElement> getBpmnElementType() {
return EndEvent.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_EVENT_END;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
EndEvent endEvent = new EndEvent();
|
BpmnXMLUtil.addXMLLocation(endEvent, xtr);
parseChildElements(getXMLElementName(), endEvent, model, xtr);
return endEvent;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
EndEvent endEvent = (EndEvent) element;
writeEventDefinitions(endEvent, endEvent.getEventDefinitions(), model, xtw);
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\EndEventXMLConverter.java
| 1
|
请完成以下Java代码
|
public void setCustomELResolvers(List<ELResolver> customELResolvers) {
this.customELResolvers = customELResolvers;
}
public ELContext getElContext(VariableScope variableScope) {
ELContext elContext = null;
if (variableScope instanceof VariableScopeImpl) {
VariableScopeImpl variableScopeImpl = (VariableScopeImpl) variableScope;
elContext = variableScopeImpl.getCachedElContext();
}
if (elContext == null) {
elContext = createElContext(variableScope);
if (variableScope instanceof VariableScopeImpl) {
((VariableScopeImpl) variableScope).setCachedElContext(elContext);
}
}
return elContext;
}
protected ActivitiElContext createElContext(VariableScope variableScope) {
return (ActivitiElContext) new ELContextBuilder()
.withResolvers(createElResolver(variableScope))
.buildWithCustomFunctions(customFunctionProviders);
}
protected ELResolver createElResolver(VariableScope variableScope) {
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(new VariableScopeElResolver(variableScope));
if (customELResolvers != null) {
customELResolvers.forEach(elResolver::add);
}
addBeansResolver(elResolver);
addBaseResolvers(elResolver);
return elResolver;
}
protected void addBeansResolver(CompositeELResolver elResolver) {
if (beans != null) {
// ACT-1102: Also expose all beans in configuration when using
// standalone activiti, not
// in spring-context
elResolver.add(new ReadOnlyMapELResolver(beans));
}
}
private void addBaseResolvers(CompositeELResolver elResolver) {
elResolver.add(new ArrayELResolver());
|
elResolver.add(new ListELResolver());
elResolver.add(new MapELResolver());
elResolver.add(new CustomMapperJsonNodeELResolver());
elResolver.add(new DynamicBeanPropertyELResolver(ItemInstance.class, "getFieldValue", "setFieldValue")); // TODO: needs verification
elResolver.add(new ELResolverReflectionBlockerDecorator(new BeanELResolver()));
}
public Map<Object, Object> getBeans() {
return beans;
}
public void setBeans(Map<Object, Object> beans) {
this.beans = beans;
}
public ELContext getElContext(Map<String, Object> availableVariables) {
CompositeELResolver elResolver = new CompositeELResolver();
addBaseResolvers(elResolver);
return new ELContextBuilder()
.withResolvers(elResolver)
.withVariables(availableVariables)
.buildWithCustomFunctions(customFunctionProviders);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\ExpressionManager.java
| 1
|
请完成以下Java代码
|
default Instant getClientSecretExpiresAt() {
return getClaimAsInstant(OAuth2ClientMetadataClaimNames.CLIENT_SECRET_EXPIRES_AT);
}
/**
* Returns the name of the Client to be presented to the End-User
* {@code (client_name)}.
* @return the name of the Client to be presented to the End-User
*/
default String getClientName() {
return getClaimAsString(OAuth2ClientMetadataClaimNames.CLIENT_NAME);
}
/**
* Returns the redirection {@code URI} values used by the Client
* {@code (redirect_uris)}.
* @return the redirection {@code URI} values used by the Client
*/
default List<String> getRedirectUris() {
return getClaimAsStringList(OAuth2ClientMetadataClaimNames.REDIRECT_URIS);
}
/**
* Returns the authentication method used by the Client for the Token Endpoint
* {@code (token_endpoint_auth_method)}.
* @return the authentication method used by the Client for the Token Endpoint
*/
default String getTokenEndpointAuthenticationMethod() {
return getClaimAsString(OAuth2ClientMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHOD);
}
/**
* Returns the OAuth 2.0 {@code grant_type} values that the Client will restrict
* itself to using {@code (grant_types)}.
* @return the OAuth 2.0 {@code grant_type} values that the Client will restrict
* itself to using
*/
default List<String> getGrantTypes() {
return getClaimAsStringList(OAuth2ClientMetadataClaimNames.GRANT_TYPES);
}
/**
* Returns the OAuth 2.0 {@code response_type} values that the Client will restrict
* itself to using {@code (response_types)}.
* @return the OAuth 2.0 {@code response_type} values that the Client will restrict
|
* itself to using
*/
default List<String> getResponseTypes() {
return getClaimAsStringList(OAuth2ClientMetadataClaimNames.RESPONSE_TYPES);
}
/**
* Returns the OAuth 2.0 {@code scope} values that the Client will restrict itself to
* using {@code (scope)}.
* @return the OAuth 2.0 {@code scope} values that the Client will restrict itself to
* using
*/
default List<String> getScopes() {
return getClaimAsStringList(OAuth2ClientMetadataClaimNames.SCOPE);
}
/**
* Returns the {@code URL} for the Client's JSON Web Key Set {@code (jwks_uri)}.
* @return the {@code URL} for the Client's JSON Web Key Set {@code (jwks_uri)}
*/
default URL getJwkSetUrl() {
return getClaimAsURL(OAuth2ClientMetadataClaimNames.JWKS_URI);
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2ClientMetadataClaimAccessor.java
| 1
|
请完成以下Java代码
|
public void setCustomerTypeOfSubset(CustomerType customerTypeOfSubset) {
this.customerTypeOfSubset = customerTypeOfSubset;
}
public CustomerType getCustomerTypeMatchesPattern() {
return customerTypeMatchesPattern;
}
public void setCustomerTypeMatchesPattern(CustomerType customerTypeMatchesPattern) {
this.customerTypeMatchesPattern = customerTypeMatchesPattern;
}
public static class Builder {
private String customerTypeString;
private CustomerType customerTypeOfSubset = CustomerType.NEW;
private CustomerType customerTypeMatchesPattern;
public Builder withCustomerTypeString(String customerTypeString) {
|
this.customerTypeString = customerTypeString;
return this;
}
public Builder withCustomerTypeOfSubset(CustomerType customerTypeOfSubset) {
this.customerTypeOfSubset = customerTypeOfSubset;
return this;
}
public Builder withCustomerTypeMatchesPattern(CustomerType customerTypeMatchesPattern) {
this.customerTypeMatchesPattern = customerTypeMatchesPattern;
return this;
}
public Customer build() {
return new Customer(customerTypeString, customerTypeOfSubset, customerTypeMatchesPattern);
}
}
}
|
repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\enums\demo\Customer.java
| 1
|
请完成以下Java代码
|
public final class VersionUtils {
/**
* Parse version of Sentinel from raw string.
*
* @param versionFull version string
* @return parsed {@link SentinelVersion} if the version is valid; empty if
* there is something wrong with the format
*/
public static Optional<SentinelVersion> parseVersion(String s) {
if (StringUtil.isBlank(s)) {
return Optional.empty();
}
try {
String versionFull = s;
SentinelVersion version = new SentinelVersion();
// postfix
int index = versionFull.indexOf("-");
if (index == 0) {
// Start with "-"
return Optional.empty();
}
if (index == versionFull.length() - 1) {
// End with "-"
} else if (index > 0) {
version.setPostfix(versionFull.substring(index + 1));
}
if (index >= 0) {
versionFull = versionFull.substring(0, index);
}
// x.x.x
int segment = 0;
int[] ver = new int[3];
while (segment < ver.length) {
|
index = versionFull.indexOf('.');
if (index < 0) {
if (versionFull.length() > 0) {
ver[segment] = Integer.valueOf(versionFull);
}
break;
}
ver[segment] = Integer.valueOf(versionFull.substring(0, index));
versionFull = versionFull.substring(index + 1);
segment ++;
}
if (ver[0] < 1) {
// Wrong format, return empty.
return Optional.empty();
} else {
return Optional.of(version
.setMajorVersion(ver[0])
.setMinorVersion(ver[1])
.setFixVersion(ver[2]));
}
} catch (Exception ex) {
// Parse fail, return empty.
return Optional.empty();
}
}
private VersionUtils() {}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\util\VersionUtils.java
| 1
|
请完成以下Java代码
|
public class AD_Column_AutoApplyValRuleInterceptor implements IModelInterceptor
{
private int m_AD_Client_ID = -1;
private final ValRuleAutoApplierService valRuleAutoApplierService;
public AD_Column_AutoApplyValRuleInterceptor(@NonNull final ValRuleAutoApplierService valRuleAutoApplierService)
{
this.valRuleAutoApplierService = valRuleAutoApplierService;
}
@Override
public void initialize(
@NonNull final IModelValidationEngine engine,
@NonNull final I_AD_Client client)
{
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
}
@Override
public int getAD_Client_ID()
{
|
return m_AD_Client_ID;
}
@Override
public void onModelChange(
@NonNull final Object recordModel,
@NonNull final ModelChangeType changeType)
{
if (!ModelChangeType.BEFORE_NEW.equals(changeType))
{
return;
}
valRuleAutoApplierService.invokeApplierFor(recordModel);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\autoapplyvalrule\interceptor\AD_Column_AutoApplyValRuleInterceptor.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: listener-demo
server:
port: 18080 # 随机端口,方便启动多个消费者
# rocketmq 配置项,对应 RocketMQProperties 配置类
rocketmq:
name-server: 127.0.0.1:9876 # RocketMQ Namesrv
management:
endpoints:
# Actuator HTTP 配置项,对应 WebEndpointProp
|
erties 配置类
web:
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
|
repos\SpringBoot-Labs-master\labx-20\labx-20-sca-bus-rocketmq-demo-listener-actuator\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
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
|
请完成以下Java代码
|
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
|
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCaptcha() {
return captcha;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
}
|
repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\validationgroup\RegistrationForm.java
| 1
|
请完成以下Java代码
|
public JdkClientHttpRequestFactoryBuilder withHttpClientCustomizer(
Consumer<HttpClient.Builder> httpClientCustomizer) {
Assert.notNull(httpClientCustomizer, "'httpClientCustomizer' must not be null");
return new JdkClientHttpRequestFactoryBuilder(getCustomizers(),
this.httpClientBuilder.withCustomizer(httpClientCustomizer));
}
/**
* Return a new {@link JdkClientHttpRequestFactoryBuilder} that applies the given
* customizer. This can be useful for applying pre-packaged customizations.
* @param customizer the customizer to apply
* @return a new {@link JdkClientHttpRequestFactoryBuilder}
* @since 4.0.0
*/
public JdkClientHttpRequestFactoryBuilder with(UnaryOperator<JdkClientHttpRequestFactoryBuilder> customizer) {
return customizer.apply(this);
}
@Override
protected JdkClientHttpRequestFactory createClientHttpRequestFactory(HttpClientSettings settings) {
|
HttpClient httpClient = this.httpClientBuilder.build(settings.withReadTimeout(null));
JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient);
PropertyMapper map = PropertyMapper.get();
map.from(settings::readTimeout).to(requestFactory::setReadTimeout);
return requestFactory;
}
static class Classes {
static final String HTTP_CLIENT = "java.net.http.HttpClient";
static boolean present(@Nullable ClassLoader classLoader) {
return ClassUtils.isPresent(HTTP_CLIENT, classLoader);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\JdkClientHttpRequestFactoryBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CLR implements CommandLineRunner {
private final AuthorRepository authorRepository;
CLR(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Override
public void run(String... args) {
insertAuthors();
listAllAuthors();
findById();
findByPartialName();
queryFindByName();
deleteAll();
}
private void deleteAll() {
this.authorRepository.deleteAll();
long count = this.authorRepository.count();
System.out.printf("deleteAll(): count = %d%n", count);
}
private void queryFindByName() {
Author author1 = this.authorRepository.queryFindByName("Josh Long").orElse(null);
Author author2 = this.authorRepository.queryFindByName("Martin Kleppmann").orElse(null);
System.out.printf("queryFindByName(): author1 = %s%n", author1);
System.out.printf("queryFindByName(): author2 = %s%n", author2);
}
private void findByPartialName() {
Author author1 = this.authorRepository.findByNameContainingIgnoreCase("sh lo").orElse(null);
Author author2 = this.authorRepository.findByNameContainingIgnoreCase("in kl").orElse(null);
System.out.printf("findByPartialName(): author1 = %s%n", author1);
System.out.printf("findByPartialName(): author2 = %s%n", author2);
}
private void findById() {
Author author1 = this.authorRepository.findById(1L).orElse(null);
Author author2 = this.authorRepository.findById(2L).orElse(null);
|
System.out.printf("findById(): author1 = %s%n", author1);
System.out.printf("findById(): author2 = %s%n", author2);
}
private void listAllAuthors() {
List<Author> authors = this.authorRepository.findAll();
for (Author author : authors) {
System.out.printf("listAllAuthors(): author = %s%n", author);
for (Book book : author.getBooks()) {
System.out.printf("\t%s%n", book);
}
}
}
private void insertAuthors() {
Author author1 = this.authorRepository.save(new Author(null, "Josh Long",
Set.of(new Book(null, "Reactive Spring"), new Book(null, "Cloud Native Java"))));
Author author2 = this.authorRepository.save(
new Author(null, "Martin Kleppmann", Set.of(new Book(null, "Designing Data Intensive Applications"))));
System.out.printf("insertAuthors(): author1 = %s%n", author1);
System.out.printf("insertAuthors(): author2 = %s%n", author2);
}
}
|
repos\spring-data-examples-main\jdbc\graalvm-native\src\main\java\example\springdata\jdbc\graalvmnative\CLR.java
| 2
|
请完成以下Java代码
|
public ForecastLineId getForecastLineId()
{
return getPurchaseCandidate().getForecastLineId();
}
private Quantity getQtyToPurchase()
{
return getPurchaseCandidate().getQtyToPurchase();
}
public boolean purchaseMatchesRequiredQty()
{
return getPurchasedQty().compareTo(getQtyToPurchase()) == 0;
}
private boolean purchaseMatchesOrExceedsRequiredQty()
{
return getPurchasedQty().compareTo(getQtyToPurchase()) >= 0;
}
public void setPurchaseOrderLineId(@NonNull final OrderAndLineId purchaseOrderAndLineId)
{
this.purchaseOrderAndLineId = purchaseOrderAndLineId;
}
public void markPurchasedIfNeeded()
{
if (purchaseMatchesOrExceedsRequiredQty())
{
purchaseCandidate.markProcessed();
}
}
public void markReqCreatedIfNeeded()
{
if (purchaseMatchesOrExceedsRequiredQty())
{
purchaseCandidate.setReqCreated(true);
}
}
@Nullable
public BigDecimal getPrice()
{
|
return purchaseCandidate.getPriceEnteredEff();
}
@Nullable
public UomId getPriceUomId()
{
return purchaseCandidate.getPriceUomId();
}
@Nullable
public Percent getDiscount()
{
return purchaseCandidate.getDiscountEff();
}
@Nullable
public String getExternalPurchaseOrderUrl()
{
return purchaseCandidate.getExternalPurchaseOrderUrl();
}
@Nullable
public ExternalId getExternalHeaderId()
{
return purchaseCandidate.getExternalHeaderId();
}
@Nullable
public ExternalSystemId getExternalSystemId()
{
return purchaseCandidate.getExternalSystemId();
}
@Nullable
public ExternalId getExternalLineId()
{
return purchaseCandidate.getExternalLineId();
}
@Nullable
public String getPOReference()
{
return purchaseCandidate.getPOReference();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java
| 1
|
请完成以下Java代码
|
public void setTimeSlotEnd (java.sql.Timestamp TimeSlotEnd)
{
set_Value (COLUMNNAME_TimeSlotEnd, TimeSlotEnd);
}
/** Get Endzeitpunkt.
@return Time when timeslot ends
*/
@Override
public java.sql.Timestamp getTimeSlotEnd ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_TimeSlotEnd);
}
/** Set Startzeitpunkt.
@param TimeSlotStart
Time when timeslot starts
*/
@Override
public void setTimeSlotStart (java.sql.Timestamp TimeSlotStart)
{
set_Value (COLUMNNAME_TimeSlotStart, TimeSlotStart);
}
/** Get Startzeitpunkt.
@return Time when timeslot starts
|
*/
@Override
public java.sql.Timestamp getTimeSlotStart ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_TimeSlotStart);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@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_S_ResourceType.java
| 1
|
请完成以下Java代码
|
public void setUsedForCustomer (final boolean UsedForCustomer)
{
set_Value (COLUMNNAME_UsedForCustomer, UsedForCustomer);
}
@Override
public boolean isUsedForCustomer()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForCustomer);
}
@Override
public void setUsedForVendor (final boolean UsedForVendor)
{
set_Value (COLUMNNAME_UsedForVendor, UsedForVendor);
}
@Override
public boolean isUsedForVendor()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForVendor);
}
@Override
|
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
@Override
public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
@Override
public java.lang.String getVendorProductNo()
{
return get_ValueAsString(COLUMNNAME_VendorProductNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product.java
| 1
|
请完成以下Java代码
|
public Date getClaimTime() {
return null;
}
@Override
public void setName(String name) {
activiti5Task.setName(name);
}
@Override
public void setLocalizedName(String name) {
activiti5Task.setLocalizedName(name);
}
@Override
public void setDescription(String description) {
activiti5Task.setDescription(description);
}
@Override
public void setLocalizedDescription(String description) {
activiti5Task.setLocalizedDescription(description);
}
@Override
public void setPriority(int priority) {
activiti5Task.setPriority(priority);
}
@Override
public void setOwner(String owner) {
activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) {
activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override
|
public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) {
activiti5Task.setCategory(category);
}
@Override
public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
}
@Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
}
|
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final JdbcExcelExporter jdbcExcelExporter = JdbcExcelExporter.builder()
.ctx(getCtx())
.columnHeaders(getColumnHeaders())
.build();
jdbcExcelExporter.setFontCharset(Font.ANSI_CHARSET);
spreadsheetExporterService.processDataFromSQL(getSql(), jdbcExcelExporter);
final File tempFile = jdbcExcelExporter.getResultFile();
final boolean backEndOrSwing = Ini.getRunMode() == RunMode.BACKEND || Ini.isSwingClient();
if (backEndOrSwing)
{
Env.startBrowser(tempFile.toURI().toString());
}
else
{
getResult().setReportData(tempFile);
}
return MSG_OK;
}
private String getSql()
{
final I_M_Product product = Services.get(IProductDAO.class).getById(getRecord_ID());
final StringBuffer sb = new StringBuffer();
sb.append("SELECT productName, CustomerLabelName, additional_produktinfos, productValue, UPC, weight, country, guaranteedaysmin, ")
.append("warehouse_temperature, productDecription, componentName, IsPackagingMaterial,componentIngredients, qtybatch, ")
.append("allergen, nutritionName, nutritionqty FROM ")
.append(tableName)
.append(" WHERE ")
.append(tableName).append(".productValue = '").append(product.getValue()).append("'")
|
.append(" ORDER BY productValue ");
return sb.toString();
}
private List<String> getColumnHeaders()
{
final List<String> columnHeaders = new ArrayList<>();
columnHeaders.add("ProductName");
columnHeaders.add("CustomerLabelName");
columnHeaders.add("Additional_produktinfos");
columnHeaders.add("ProductValue");
columnHeaders.add("UPC");
columnHeaders.add("NetWeight");
columnHeaders.add("Country");
columnHeaders.add("ShelfLifeDays");
columnHeaders.add("Warehouse_temperature");
columnHeaders.add("ProductDescription");
columnHeaders.add("M_BOMProduct_ID");
columnHeaders.add("IsPackagingMaterial");
columnHeaders.add("Ingredients");
columnHeaders.add("QtyBatch");
columnHeaders.add("Allergen");
columnHeaders.add("M_Product_Nutrition_ID");
columnHeaders.add("NutritionQty");
return columnHeaders;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\product\process\ExportProductSpecifications.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
KafkaTemplate<Object, Object> kafkaTemplate(ProducerFactory<Object, Object> pf) {
return new KafkaTemplate<>(pf);
}
// tag::beans[]
@Bean
ReplyingKafkaTemplate<String, String, String> template(
ProducerFactory<String, String> pf,
ConcurrentKafkaListenerContainerFactory<String, String> factory) {
ConcurrentMessageListenerContainer<String, String> replyContainer =
factory.createContainer("replies");
replyContainer.getContainerProperties().setGroupId("request.replies");
ReplyingKafkaTemplate<String, String, String> template =
new ReplyingKafkaTemplate<>(pf, replyContainer);
template.setMessageConverter(new ByteArrayJacksonJsonMessageConverter());
template.setDefaultTopic("requests");
return template;
}
// end::beans[]
@Bean
ApplicationRunner runner(ReplyingKafkaTemplate<String, String, String> template) {
return args -> {
// tag::sendReceive[]
RequestReplyTypedMessageFuture<String, String, Thing> future1 =
template.sendAndReceive(MessageBuilder.withPayload("getAThing").build(),
new ParameterizedTypeReference<Thing>() { });
log.info(future1.getSendFuture().get(10, TimeUnit.SECONDS).getRecordMetadata().toString());
Thing thing = future1.get(10, TimeUnit.SECONDS).getPayload();
log.info(thing.toString());
RequestReplyTypedMessageFuture<String, String, List<Thing>> future2 =
template.sendAndReceive(MessageBuilder.withPayload("getThings").build(),
new ParameterizedTypeReference<List<Thing>>() { });
log.info(future2.getSendFuture().get(10, TimeUnit.SECONDS).getRecordMetadata().toString());
List<Thing> things = future2.get(10, TimeUnit.SECONDS).getPayload();
things.forEach(thing1 -> log.info(thing1.toString()));
// end::sendReceive[]
};
}
@KafkaListener(id = "myId", topics = "requests", properties = "auto.offset.reset:earliest")
@SendTo
public byte[] listen(String in) {
|
log.info(in);
if (in.equals("\"getAThing\"")) {
return ("{\"thingProp\":\"someValue\"}").getBytes();
}
if (in.equals("\"getThings\"")) {
return ("[{\"thingProp\":\"someValue1\"},{\"thingProp\":\"someValue2\"}]").getBytes();
}
return in.toUpperCase().getBytes();
}
public static class Thing {
private String thingProp;
public String getThingProp() {
return this.thingProp;
}
public void setThingProp(String thingProp) {
this.thingProp = thingProp;
}
@Override
public String toString() {
return "Thing [thingProp=" + this.thingProp + "]";
}
}
}
|
repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\requestreply\Application.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class EntityDescription implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String description;
@Any
@AnyDiscriminator(DiscriminatorType.STRING)
@AnyDiscriminatorValue(discriminator = "S", entity = Employee.class)
@AnyDiscriminatorValue(discriminator = "I", entity = Phone.class)
@AnyKeyJavaClass(Integer.class)
@Column(name = "entity_type")
@JoinColumn(name = "entity_id")
private Serializable entity;
public EntityDescription() {
}
public EntityDescription(String description, Serializable entity) {
this.description = description;
this.entity = entity;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
|
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Serializable getEntity() {
return entity;
}
public void setEntity(Serializable entity) {
this.entity = entity;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\pojo\EntityDescription.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String code;
private double price;
public Product() {
}
public Product(String code, double price) {
this.code = code;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
|
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-jpa-3\src\main\java\com\baeldung\hibernate\dirtychecking\entity\Product.java
| 2
|
请完成以下Java代码
|
protected Map<String, String> extractExternalSystemParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig)
{
final ExternalSystemPCMConfig pcmConfig = ExternalSystemPCMConfig.cast(externalSystemParentConfig.getChildConfig());
final OrgId orgId = pcmConfig.getOrgId();
final BPartnerLocationId orgBPartnerLocationId = orgDAO.getOrgInfoById(orgId).getOrgBPartnerLocationId();
Check.assumeNotNull(orgBPartnerLocationId, "AD_Org_ID={} needs to have an Organisation Business Partner Location ID", OrgId.toRepoId(orgId));
return invokePCMService.getParameters(pcmConfig, externalRequest, orgBPartnerLocationId.getBpartnerId());
}
@Override
protected String getTabName()
{
return getExternalSystemType().getValue();
}
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.ProCareManagement;
|
}
@Override
protected long getSelectedRecordCount(final IProcessPreconditionsContext context)
{
return context.getSelectedIncludedRecords()
.stream()
.filter(recordRef -> I_ExternalSystem_Config_ProCareManagement.Table_Name.equals(recordRef.getTableName()))
.count();
}
@Override
protected String getOrgCode(@NonNull final ExternalSystemParentConfig externalSystemParentConfig)
{
final ExternalSystemPCMConfig pcmConfig = ExternalSystemPCMConfig.cast(externalSystemParentConfig.getChildConfig());
final OrgId orgId = pcmConfig.getOrgId();
return orgDAO.getById(orgId).getValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokePCMAction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String showUpdateTodoPage(@RequestParam long id, ModelMap model) {
Todo todo = todoService.getTodoById(id).get();
model.put("todo", todo);
return "todo";
}
@RequestMapping(value = "/update-todo", method = RequestMethod.POST)
public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) {
if (result.hasErrors()) {
return "todo";
}
todo.setUserName(getLoggedInUserName(model));
todoService.updateTodo(todo);
|
return "redirect:/list-todos";
}
@RequestMapping(value = "/add-todo", method = RequestMethod.POST)
public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) {
if (result.hasErrors()) {
return "todo";
}
todo.setUserName(getLoggedInUserName(model));
todoService.saveTodo(todo);
return "redirect:/list-todos";
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDB\src\main\java\spring\hibernate\controller\TodoController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required = false) String keyword,
@RequestParam(required = false, defaultValue = "0") Integer pageNum,
@RequestParam(required = false, defaultValue = "5") Integer pageSize) {
Page<EsProduct> esProductPage = esProductService.search(keyword, pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(esProductPage));
}
@ApiOperation(value = "综合搜索、筛选、排序")
@ApiImplicitParam(name = "sort", value = "排序字段:0->按相关度;1->按新品;2->按销量;3->价格从低到高;4->价格从高到低",
defaultValue = "0", allowableValues = "0,1,2,3,4", paramType = "query", dataType = "integer")
@RequestMapping(value = "/search", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required = false) String keyword,
@RequestParam(required = false) Long brandId,
@RequestParam(required = false) Long productCategoryId,
@RequestParam(required = false, defaultValue = "0") Integer pageNum,
@RequestParam(required = false, defaultValue = "5") Integer pageSize,
@RequestParam(required = false, defaultValue = "0") Integer sort) {
Page<EsProduct> esProductPage = esProductService.search(keyword, brandId, productCategoryId, pageNum, pageSize, sort);
return CommonResult.success(CommonPage.restPage(esProductPage));
}
@ApiOperation(value = "根据商品id推荐商品")
@RequestMapping(value = "/recommend/{id}", method = RequestMethod.GET)
|
@ResponseBody
public CommonResult<CommonPage<EsProduct>> recommend(@PathVariable Long id,
@RequestParam(required = false, defaultValue = "0") Integer pageNum,
@RequestParam(required = false, defaultValue = "5") Integer pageSize) {
Page<EsProduct> esProductPage = esProductService.recommend(id, pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(esProductPage));
}
@ApiOperation(value = "获取搜索的相关品牌、分类及筛选属性")
@RequestMapping(value = "/search/relate", method = RequestMethod.GET)
@ResponseBody
public CommonResult<EsProductRelatedInfo> searchRelatedInfo(@RequestParam(required = false) String keyword) {
EsProductRelatedInfo productRelatedInfo = esProductService.searchRelatedInfo(keyword);
return CommonResult.success(productRelatedInfo);
}
}
|
repos\mall-master\mall-search\src\main\java\com\macro\mall\search\controller\EsProductController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getBrokerUrl() {
return this.brokerUrl;
}
public void setBrokerUrl(@Nullable String brokerUrl) {
this.brokerUrl = brokerUrl;
}
public @Nullable String getUser() {
return this.user;
}
public void setUser(@Nullable String user) {
this.user = user;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public Embedded getEmbedded() {
return this.embedded;
}
public Duration getCloseTimeout() {
return this.closeTimeout;
}
public void setCloseTimeout(Duration closeTimeout) {
this.closeTimeout = closeTimeout;
}
public boolean isNonBlockingRedelivery() {
return this.nonBlockingRedelivery;
}
public void setNonBlockingRedelivery(boolean nonBlockingRedelivery) {
this.nonBlockingRedelivery = nonBlockingRedelivery;
}
public Duration getSendTimeout() {
return this.sendTimeout;
}
public void setSendTimeout(Duration sendTimeout) {
this.sendTimeout = sendTimeout;
}
public JmsPoolConnectionFactoryProperties getPool() {
return this.pool;
}
public Packages getPackages() {
return this.packages;
}
String determineBrokerUrl() {
if (this.brokerUrl != null) {
return this.brokerUrl;
}
if (this.embedded.isEnabled()) {
return DEFAULT_EMBEDDED_BROKER_URL;
}
return DEFAULT_NETWORK_BROKER_URL;
}
|
/**
* Configuration for an embedded ActiveMQ broker.
*/
public static class Embedded {
/**
* Whether to enable embedded mode if the ActiveMQ Broker is available.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public static class Packages {
/**
* Whether to trust all packages.
*/
private @Nullable Boolean trustAll;
/**
* List of specific packages to trust (when not trusting all packages).
*/
private List<String> trusted = new ArrayList<>();
public @Nullable Boolean getTrustAll() {
return this.trustAll;
}
public void setTrustAll(@Nullable Boolean trustAll) {
this.trustAll = trustAll;
}
public List<String> getTrusted() {
return this.trusted;
}
public void setTrusted(List<String> trusted) {
this.trusted = trusted;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQProperties.java
| 2
|
请完成以下Java代码
|
private Date generateExpirationDate() {
return new Date(System.currentTimeMillis() + Const.EXPIRATION_TIME * 1000);
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
return (lastPasswordReset != null && created.before(lastPasswordReset));
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.HS512, Const.SECRET )
.compact();
}
|
public Boolean canTokenBeRefreshed(String token) {
return !isTokenExpired(token);
}
public String refreshToken(String token) {
String refreshedToken;
try {
final Claims claims = getClaimsFromToken(token);
claims.put(CLAIM_KEY_CREATED, new Date());
refreshedToken = generateToken(claims);
} catch (Exception e) {
refreshedToken = null;
}
return refreshedToken;
}
public Boolean validateToken(String token, UserDetails userDetails) {
User user = (User) userDetails;
final String username = getUsernameFromToken(token);
return (
username.equals(user.getUsername())
&& !isTokenExpired(token)
);
}
}
|
repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\java\cn\codesheep\springbt_security_jwt\util\JwtTokenUtil.java
| 1
|
请完成以下Java代码
|
public void setRequestHandler(CsrfTokenRequestHandler requestHandler) {
Assert.notNull(requestHandler, "requestHandler cannot be null");
this.requestHandler = requestHandler;
}
/**
* Constant time comparison to prevent against timing attacks.
* @param expected
* @param actual
* @return
*/
private static boolean equalsConstantTime(String expected, @Nullable String actual) {
if (expected == actual) {
return true;
}
if (expected == null || actual == null) {
return false;
}
// Encode after ensure that the string is not null
byte[] expectedBytes = Utf8.encode(expected);
|
byte[] actualBytes = Utf8.encode(actual);
return MessageDigest.isEqual(expectedBytes, actualBytes);
}
private static final class DefaultRequiresCsrfMatcher implements RequestMatcher {
private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));
@Override
public boolean matches(HttpServletRequest request) {
return !this.allowedMethods.contains(request.getMethod());
}
@Override
public String toString() {
return "IsNotHttpMethod " + this.allowedMethods;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfFilter.java
| 1
|
请完成以下Java代码
|
public final List<I_M_HU> getAssignedHUs()
{
final String trxName = getTrxName();
if (assignedHUs != null && trxManager.isSameTrxName(trxName, assignedHUsTrxName))
{
assignedHUs = null;
}
if (assignedHUs == null)
{
final Object documentLineModel = getDocumentLineModel();
assignedHUs = huAssignmentDAO.retrieveTopLevelHUsForModel(documentLineModel, trxName);
assignedHUsTrxName = trxName;
}
return assignedHUs;
}
/**
* Invokes {@link IHUAssignmentBL#assignHUs(Object, Collection, String)}.
*/
@Override
public final void addAssignedHUs(final Collection<I_M_HU> husToAssign)
{
huAssignmentBL.assignHUs(getDocumentLineModel(), husToAssign, getTrxName());
//
// Reset cached values
assignedHUs = null;
markStorageStaled();
}
private final void markStorageStaled()
{
if (productStorage == null)
{
return;
}
productStorage.markStaled();
}
@Override
public final void removeAssignedHUs(final Collection<I_M_HU> husToUnassign)
{
final Object documentLineModel = getDocumentLineModel();
final String trxName = getTrxName();
final Set<HuId> huIdsToUnassign = husToUnassign.stream()
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
|
.collect(Collectors.toSet());
huAssignmentBL.unassignHUs(documentLineModel, huIdsToUnassign, trxName);
deleteAllocations(husToUnassign);
//
// Reset cached values
assignedHUs = null;
markStorageStaled();
}
@Override
public final void destroyAssignedHU(final I_M_HU huToDestroy)
{
Check.assumeNotNull(huToDestroy, "huToDestroy not null");
InterfaceWrapperHelper.setThreadInheritedTrxName(huToDestroy);
removeAssignedHUs(Collections.singleton(huToDestroy));
final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(huToDestroy);
final IHUContext huContext = Services.get(IHandlingUnitsBL.class).createMutableHUContext(contextProvider);
handlingUnitsBL.markDestroyed(huContext, huToDestroy);
}
@Override
public String toString()
{
return "AbstractHUAllocations [contextProvider=" + contextProvider + ", documentLineModel=" + documentLineModel + ", productStorage=" + productStorage + ", assignedHUs=" + assignedHUs + ", assignedHUsTrxName=" + assignedHUsTrxName + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUAllocations.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public TaskBuilder taskDefinitionId(String taskDefinitionId) {
this.taskDefinitionId = taskDefinitionId;
return this;
}
@Override
public TaskBuilder taskDefinitionKey(String taskDefinitionKey) {
this.taskDefinitionKey = taskDefinitionKey;
return this;
}
@Override
public TaskBuilder identityLinks(Set<? extends IdentityLinkInfo> identityLinks) {
this.identityLinks = identityLinks;
return this;
}
@Override
public TaskBuilder scopeId(String scopeId) {
this.scopeId = scopeId;
return this;
}
@Override
public TaskBuilder scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public int getPriority() {
return priority;
}
@Override
public String getOwner() {
return ownerId;
}
@Override
public String getAssignee() {
|
return assigneeId;
}
@Override
public String getTaskDefinitionId() {
return taskDefinitionId;
}
@Override
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
@Override
public Date getDueDate() {
return dueDate;
}
@Override
public String getCategory() {
return category;
}
@Override
public String getParentTaskId() {
return parentTaskId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getFormKey() {
return formKey;
}
@Override
public Set<? extends IdentityLinkInfo> getIdentityLinks() {
return identityLinks;
}
@Override
public String getScopeId() {
return this.scopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseTaskBuilderImpl.java
| 2
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((backCoverArtUrl == null) ? 0 : backCoverArtUrl.hashCode());
result = prime * result + ((frontCoverArtUrl == null) ? 0 : frontCoverArtUrl.hashCode());
result = prime * result + ((upcCode == null) ? 0 : upcCode.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CoverArt other = (CoverArt) obj;
|
if (backCoverArtUrl == null) {
if (other.backCoverArtUrl != null)
return false;
} else if (!backCoverArtUrl.equals(other.backCoverArtUrl))
return false;
if (frontCoverArtUrl == null) {
if (other.frontCoverArtUrl != null)
return false;
} else if (!frontCoverArtUrl.equals(other.frontCoverArtUrl))
return false;
if (upcCode == null) {
if (other.upcCode != null)
return false;
} else if (!upcCode.equals(other.upcCode))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-libraries\src\main\java\com\baeldung\hibernate\types\CoverArt.java
| 1
|
请完成以下Java代码
|
public static <T> void printRandom(T[] elements, char delimiter) {
Collections.shuffle(Arrays.asList(elements));
printArray(elements, delimiter);
}
private static <T> void swap(T[] elements, int a, int b) {
T tmp = elements[a];
elements[a] = elements[b];
elements[b] = tmp;
}
private static <T> void printArray(T[] elements, char delimiter) {
String delimiterSpace = delimiter + " ";
for(int i = 0; i < elements.length; i++) {
System.out.print(elements[i] + delimiterSpace);
}
System.out.print('\n');
}
public static void main(String[] argv) {
|
Integer[] elements = {1,2,3,4};
System.out.println("Rec:");
printAllRecursive(elements, ';');
System.out.println("Iter:");
printAllIterative(elements.length, elements, ';');
System.out.println("Orderes:");
printAllOrdered(elements, ';');
System.out.println("Random:");
printRandom(elements, ';');
System.out.println("Random:");
printRandom(elements, ';');
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-1\src\main\java\com\baeldung\algorithms\permutation\Permutation.java
| 1
|
请完成以下Java代码
|
public void removeRequest(HttpServletRequest request, HttpServletResponse response) {
Cookie removeSavedRequestCookie = new Cookie(COOKIE_NAME, "");
removeSavedRequestCookie.setSecure(request.isSecure());
removeSavedRequestCookie.setHttpOnly(true);
removeSavedRequestCookie.setPath(getCookiePath(request));
removeSavedRequestCookie.setMaxAge(0);
response.addCookie(removeSavedRequestCookie);
}
private static String encodeCookie(String cookieValue) {
return Base64.getEncoder().encodeToString(cookieValue.getBytes());
}
private @Nullable String decodeCookie(String encodedCookieValue) {
try {
return new String(Base64.getDecoder().decode(encodedCookieValue.getBytes()));
}
catch (IllegalArgumentException ex) {
this.logger.debug("Failed decode cookie value " + encodedCookieValue);
return null;
}
}
private static String getCookiePath(HttpServletRequest request) {
String contextPath = request.getContextPath();
return (StringUtils.hasLength(contextPath)) ? contextPath : "/";
}
private boolean matchesSavedRequest(HttpServletRequest request, @Nullable SavedRequest savedRequest) {
if (savedRequest == null) {
return false;
|
}
String currentUrl = UrlUtils.buildFullRequestUrl(request);
return savedRequest.getRedirectUrl().equals(currentUrl);
}
/**
* Allows selective use of saved requests for a subset of requests. By default any
* request will be cached by the {@code saveRequest} method.
* <p>
* If set, only matching requests will be cached.
* @param requestMatcher a request matching strategy which defines which requests
* should be cached.
*/
public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher should not be null");
this.requestMatcher = requestMatcher;
}
/**
* Sets the {@link Consumer}, allowing customization of cookie.
* @param cookieCustomizer customize for cookie
* @since 6.4
*/
public void setCookieCustomizer(Consumer<Cookie> cookieCustomizer) {
Assert.notNull(cookieCustomizer, "cookieCustomizer cannot be null");
this.cookieCustomizer = cookieCustomizer;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\CookieRequestCache.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("handlers", handlers)
.toString();
}
public void addHandler(final IFlatrateTermEventListener handler)
{
Check.assumeNotNull(handler, "handler not null");
handlers.addIfAbsent(handler);
}
@Override
public void beforeFlatrateTermReactivate(final I_C_Flatrate_Term term)
{
handlers.forEach(h -> h.beforeFlatrateTermReactivate(term));
}
|
@Override
public void afterSaveOfNextTermForPredecessor(I_C_Flatrate_Term next, I_C_Flatrate_Term predecessor)
{
handlers.forEach(h -> h.afterSaveOfNextTermForPredecessor(next, predecessor));
}
@Override
public void afterFlatrateTermEnded(I_C_Flatrate_Term term)
{
handlers.forEach(h -> h.afterFlatrateTermEnded(term));
}
@Override
public void beforeSaveOfNextTermForPredecessor(I_C_Flatrate_Term next, I_C_Flatrate_Term predecessor)
{
handlers.forEach(h -> h.beforeSaveOfNextTermForPredecessor(next,predecessor));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\CompositeFlatrateTermEventListener.java
| 1
|
请完成以下Java代码
|
class ColumnNode extends DancingNode {
int size;
String name;
ColumnNode(String n) {
super();
size = 0;
name = n;
C = this;
}
void cover() {
unlinkLR();
for (DancingNode i = this.D; i != this; i = i.D) {
for (DancingNode j = i.R; j != i; j = j.R) {
|
j.unlinkUD();
j.C.size--;
}
}
}
void uncover() {
for (DancingNode i = this.U; i != this; i = i.U) {
for (DancingNode j = i.L; j != i; j = j.L) {
j.C.size++;
j.relinkUD();
}
}
relinkLR();
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\ColumnNode.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@ApiModelProperty(example = "http://localhost:8182/repository/process-definition/3")
public String getProcessDefinitionUrl() {
return processDefinitionUrl;
}
public void setProcessDefinitionUrl(String processDefinitionUrl) {
this.processDefinitionUrl = processDefinitionUrl;
}
@ApiModelProperty(example = "6")
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/task/6")
public String getTaskUrl() {
return taskUrl;
|
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
public List<RestFormProperty> getFormProperties() {
return formProperties;
}
public void setFormProperties(List<RestFormProperty> formProperties) {
this.formProperties = formProperties;
}
public void addFormProperty(RestFormProperty formProperty) {
formProperties.add(formProperty);
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\form\FormDataResponse.java
| 2
|
请完成以下Java代码
|
public CountResultDto getHistoricDecisionInstancesCount(UriInfo uriInfo) {
HistoricDecisionInstanceQueryDto queryDto = new HistoricDecisionInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricDecisionInstancesCount(queryDto);
}
public CountResultDto queryHistoricDecisionInstancesCount(HistoricDecisionInstanceQueryDto queryDto) {
HistoricDecisionInstanceQuery query = queryDto.toQuery(processEngine);
long count = query.count();
return new CountResultDto(count);
}
@Override
public BatchDto deleteAsync(DeleteHistoricDecisionInstancesDto dto) {
HistoricDecisionInstanceQuery decisionInstanceQuery = null;
if (dto.getHistoricDecisionInstanceQuery() != null) {
decisionInstanceQuery = dto.getHistoricDecisionInstanceQuery().toQuery(processEngine);
}
try {
List<String> historicDecisionInstanceIds = dto.getHistoricDecisionInstanceIds();
String deleteReason = dto.getDeleteReason();
Batch batch = processEngine.getHistoryService().deleteHistoricDecisionInstancesAsync(historicDecisionInstanceIds, decisionInstanceQuery, deleteReason);
return BatchDto.fromBatch(batch);
}
catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
@Override
public BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricDecisionInstancesDto dto) {
HistoryService historyService = processEngine.getHistoryService();
HistoricDecisionInstanceQuery historicDecisionInstanceQuery = null;
if (dto.getHistoricDecisionInstanceQuery() != null) {
historicDecisionInstanceQuery = dto.getHistoricDecisionInstanceQuery().toQuery(processEngine);
}
SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builder =
historyService.setRemovalTimeToHistoricDecisionInstances();
if (dto.isCalculatedRemovalTime()) {
|
builder.calculatedRemovalTime();
}
Date removalTime = dto.getAbsoluteRemovalTime();
if (dto.getAbsoluteRemovalTime() != null) {
builder.absoluteRemovalTime(removalTime);
}
if (dto.isClearedRemovalTime()) {
builder.clearedRemovalTime();
}
builder.byIds(dto.getHistoricDecisionInstanceIds());
builder.byQuery(historicDecisionInstanceQuery);
if (dto.isHierarchical()) {
builder.hierarchical();
}
Batch batch = builder.executeAsync();
return BatchDto.fromBatch(batch);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricDecisionInstanceRestServiceImpl.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final PickingSlotRow rowToProcess = getSingleSelectedRow();
final ImmutableSet<HuId> hUs = filterOutInvalidHUs(rowToProcess);
final ShipmentScheduleId shipmentScheduleId = null;
//noinspection ConstantConditions
pickingCandidateService.processForHUIds(hUs, shipmentScheduleId);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
|
invalidatePickingSlotsView();
invalidatePackablesView();
}
private boolean checkIsEmpty(final PickingSlotRow pickingSlotRowOrHU)
{
Check.assume(pickingSlotRowOrHU.isPickedHURow(), "Was expecting an HuId but found none!");
if (pickingSlotRowOrHU.getHuQtyCU() != null && pickingSlotRowOrHU.getHuQtyCU().signum() > 0)
{
return false;
}
final I_M_HU hu = handlingUnitsBL.getById(pickingSlotRowOrHU.getHuId());
return handlingUnitsBL.isEmptyStorage(hu);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_M_Picking_Candidate_Process.java
| 1
|
请完成以下Java代码
|
public ITranslatableString toTranslatableString()
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return TranslatableStrings.builder().appendPercent(percent).build();
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return TranslatableStrings.builder().appendQty(qty.toBigDecimal(), qty.getUOMSymbol()).build();
}
else
{
// shall not happen
return TranslatableStrings.empty();
}
}
public Quantity addTo(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return qtyBase.add(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return qtyBase.add(qty);
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
}
}
public Quantity subtractFrom(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return qtyBase.subtract(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return qtyBase.subtract(qty);
|
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
}
}
public IssuingToleranceSpec convertQty(@NonNull final UnaryOperator<Quantity> qtyConverter)
{
if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qtyConv = qtyConverter.apply(qty);
if (qtyConv.equals(qty))
{
return this;
}
return toBuilder().qty(qtyConv).build();
}
else
{
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\IssuingToleranceSpec.java
| 1
|
请完成以下Java代码
|
public void setQtyLUFromQtyTU(final IHUPackingAware record)
{
final BigDecimal qtyTUs = record.getQtyTU();
if (qtyTUs == null)
{
return;
}
final BigDecimal capacity = calculateLUCapacity(record);
if (capacity == null)
{
return;
}
final BigDecimal qtyLUs = qtyTUs.divide(capacity, RoundingMode.UP);
record.setQtyLU(qtyLUs);
}
@Override
|
public void validateLUQty(final BigDecimal luQty)
{
final int maxLUQty = sysConfigBL.getIntValue(SYS_CONFIG_MAXQTYLU, SYS_CONFIG_MAXQTYLU_DEFAULT_VALUE);
if (luQty != null && luQty.compareTo(BigDecimal.valueOf(maxLUQty)) > 0)
{
throw new AdempiereException(MSG_MAX_LUS_EXCEEDED);
}
}
private I_C_UOM extractUOMOrNull(final IHUPackingAware huPackingAware)
{
final int uomId = huPackingAware.getC_UOM_ID();
return uomId > 0
? uomDAO.getById(uomId)
: null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUPackingAwareBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable String getLocation() {
return this.location;
}
public void setLocation(@Nullable String location) {
this.location = location;
}
public DataSize getMaxFileSize() {
return this.maxFileSize;
}
public void setMaxFileSize(DataSize maxFileSize) {
this.maxFileSize = maxFileSize;
}
public DataSize getMaxRequestSize() {
return this.maxRequestSize;
}
public void setMaxRequestSize(DataSize maxRequestSize) {
this.maxRequestSize = maxRequestSize;
}
public DataSize getFileSizeThreshold() {
return this.fileSizeThreshold;
}
public void setFileSizeThreshold(DataSize fileSizeThreshold) {
this.fileSizeThreshold = fileSizeThreshold;
|
}
public boolean isResolveLazily() {
return this.resolveLazily;
}
public void setResolveLazily(boolean resolveLazily) {
this.resolveLazily = resolveLazily;
}
public boolean isStrictServletCompliance() {
return this.strictServletCompliance;
}
public void setStrictServletCompliance(boolean strictServletCompliance) {
this.strictServletCompliance = strictServletCompliance;
}
/**
* Create a new {@link MultipartConfigElement} using the properties.
* @return a new {@link MultipartConfigElement} configured using there properties
*/
public MultipartConfigElement createMultipartConfig() {
MultipartConfigFactory factory = new MultipartConfigFactory();
PropertyMapper map = PropertyMapper.get();
map.from(this.fileSizeThreshold).to(factory::setFileSizeThreshold);
map.from(this.location).whenHasText().to(factory::setLocation);
map.from(this.maxRequestSize).to(factory::setMaxRequestSize);
map.from(this.maxFileSize).to(factory::setMaxFileSize);
return factory.createMultipartConfig();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\MultipartProperties.java
| 2
|
请完成以下Java代码
|
public int getA_Asset_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set A_Asset_Info_Lic_ID.
@param A_Asset_Info_Lic_ID A_Asset_Info_Lic_ID */
public void setA_Asset_Info_Lic_ID (int A_Asset_Info_Lic_ID)
{
if (A_Asset_Info_Lic_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Asset_Info_Lic_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Asset_Info_Lic_ID, Integer.valueOf(A_Asset_Info_Lic_ID));
}
/** Get A_Asset_Info_Lic_ID.
@return A_Asset_Info_Lic_ID */
public int getA_Asset_Info_Lic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Info_Lic_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(getA_Asset_Info_Lic_ID()));
}
/** Set Issuing Agency.
@param A_Issuing_Agency Issuing Agency */
public void setA_Issuing_Agency (String A_Issuing_Agency)
{
set_Value (COLUMNNAME_A_Issuing_Agency, A_Issuing_Agency);
}
/** Get Issuing Agency.
@return Issuing Agency */
public String getA_Issuing_Agency ()
{
return (String)get_Value(COLUMNNAME_A_Issuing_Agency);
}
/** Set License Fee.
@param A_License_Fee License Fee */
public void setA_License_Fee (BigDecimal A_License_Fee)
{
set_Value (COLUMNNAME_A_License_Fee, A_License_Fee);
}
/** Get License Fee.
@return License Fee */
public BigDecimal getA_License_Fee ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_License_Fee);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set License No.
@param A_License_No License No */
public void setA_License_No (String A_License_No)
{
set_Value (COLUMNNAME_A_License_No, A_License_No);
}
/** Get License No.
@return License No */
public String getA_License_No ()
{
return (String)get_Value(COLUMNNAME_A_License_No);
}
/** Set Policy Renewal Date.
@param A_Renewal_Date Policy Renewal Date */
public void setA_Renewal_Date (Timestamp A_Renewal_Date)
{
set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date);
}
|
/** Get Policy Renewal Date.
@return Policy Renewal Date */
public Timestamp getA_Renewal_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date);
}
/** Set Account State.
@param A_State
State of the Credit Card or Account holder
*/
public void setA_State (String A_State)
{
set_Value (COLUMNNAME_A_State, A_State);
}
/** Get Account State.
@return State of the Credit Card or Account holder
*/
public String getA_State ()
{
return (String)get_Value(COLUMNNAME_A_State);
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Lic.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public IPage<DictVO> selectDictPage(IPage<DictVO> page, DictVO dict) {
return page.setRecords(baseMapper.selectDictPage(page, dict));
}
@Override
public List<DictVO> tree() {
return ForestNodeMerger.merge(baseMapper.tree());
}
@Override
@Cacheable(cacheNames = DICT_VALUE, key = "#code+'_'+#dictKey")
public String getValue(String code, Integer dictKey) {
return Func.toStr(baseMapper.getValue(code, dictKey), StringPool.EMPTY);
}
@Override
@Cacheable(cacheNames = DICT_LIST, key = "#code")
|
public List<Dict> getList(String code) {
return baseMapper.getList(code);
}
@Override
@CacheEvict(cacheNames = {DICT_LIST, DICT_VALUE}, allEntries = true)
public boolean submit(Dict dict) {
LambdaQueryWrapper<Dict> lqw = Wrappers.<Dict>query().lambda().eq(Dict::getCode, dict.getCode()).eq(Dict::getDictKey, dict.getDictKey());
Long cnt = baseMapper.selectCount((Func.isEmpty(dict.getId())) ? lqw : lqw.notIn(Dict::getId, dict.getId()));
if (cnt > 0) {
throw new ServiceException("当前字典键值已存在!");
}
return saveOrUpdate(dict);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\DictServiceImpl.java
| 2
|
请完成以下Java代码
|
private void init()
{
purchaseOrder = orderDAO.getById(selectedPurchaseOrderId);
final Optional<List<I_C_Order>> salesOrders = getSalesOrders();
salesOrderRecordRefs = salesOrders.map(this::getSalesOrdersRecordRef).orElse(ImmutableMap.of());
bPartnerRecordRefs = salesOrders.map(this::getSalesOrderPartnersRecordRef).orElse(ImmutableSet.of());
final Set<OrderId> salesOrderIds = salesOrderRecordRefs.keySet()
.stream()
.map(TableRecordReference::getRecord_ID)
.map(OrderId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
prescriptionRequestRecordRefs = getAlbertaPrescriptionsRecordRefs(salesOrderIds).orElse(ImmutableMap.of());
}
@NonNull
private Optional<List<I_C_Order>> getSalesOrders()
{
final ImmutableSet.Builder<OrderId> salesOrderIds = ImmutableSet.builder();
salesOrderIds.addAll(orderDAO.getSalesOrderIdsViaPOAllocation(selectedPurchaseOrderId));
if (purchaseOrder.getLink_Order_ID() > 0) // there might be no C_PO_OrderLine_Alloc records, but a 1:1 linked sales order
{
salesOrderIds.add(OrderId.ofRepoId(purchaseOrder.getLink_Order_ID()));
}
purchaseCandidateRepository.getAllByPurchaseOrderId(selectedPurchaseOrderId)
.stream()
.map(PurchaseCandidate::getSalesOrderAndLineIdOrNull)
.filter(Objects::nonNull)
.map(OrderAndLineId::getOrderId)
.forEach(salesOrderIds::add);
return Optional.of(orderDAO.getByIds(salesOrderIds.build()));
}
|
@NonNull
private Map<TableRecordReference, I_C_Order> getSalesOrdersRecordRef(@NonNull final List<I_C_Order> salesOrders)
{
return salesOrders
.stream()
.collect(ImmutableMap.toImmutableMap(order -> TableRecordReference.of(I_C_Order.Table_Name, order.getC_Order_ID()),
Function.identity()));
}
@NonNull
private ImmutableSet<TableRecordReference> getSalesOrderPartnersRecordRef(@NonNull final List<I_C_Order> salesOrders)
{
return salesOrders
.stream()
.map(order -> TableRecordReference.of(I_C_BPartner.Table_Name, order.getC_BPartner_ID()))
.collect(ImmutableSet.toImmutableSet());
}
@NonNull
private Optional<Map<TableRecordReference, I_Alberta_PrescriptionRequest>> getAlbertaPrescriptionsRecordRefs(@NonNull final Set<OrderId> salesOrderIds)
{
if (salesOrderIds.isEmpty())
{
return Optional.empty();
}
return Optional.of(albertaPrescriptionRequestDAO.getByOrderIds(salesOrderIds)
.stream()
.collect(ImmutableMap.toImmutableMap(prescription -> TableRecordReference.of(I_Alberta_PrescriptionRequest.Table_Name, prescription.getAlberta_PrescriptionRequest_ID()),
Function.identity())));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\attachmenteditor\OrderAttachmentRowsLoader.java
| 1
|
请完成以下Java代码
|
public final class InvoiceAcct
{
@Getter @NonNull private final InvoiceId invoiceId;
@Getter @NonNull private final OrgId orgId;
@Getter @NonNull private final ImmutableList<InvoiceAcctRule> rulesOrdered;
@Builder
private InvoiceAcct(
final @NonNull InvoiceId invoiceId,
final @NonNull OrgId orgId,
final @NonNull ImmutableList<InvoiceAcctRule> rules)
{
Check.assumeNotEmpty(rules, "rulesOrdered not empty");
Check.assume(orgId.isRegular(), "org is set");
rules.forEach(rule -> rule.assertInvoiceId(invoiceId));
this.invoiceId = invoiceId;
this.orgId = orgId;
this.rulesOrdered = rules.stream()
.sorted(Comparator.comparing(InvoiceAcctRule::getMatcher, InvoiceAcctRuleMatcher.ORDER_FROM_SPECIFIC_TO_GENERIC))
|
.collect(ImmutableList.toImmutableList());
}
@NonNull
public Optional<ElementValueId> getElementValueId(
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final AccountConceptualName accountConceptualName,
@Nullable final InvoiceAndLineId invoiceAndLineId)
{
return this.rulesOrdered.stream()
.filter(rule -> rule.matches(acctSchemaId, accountConceptualName, invoiceAndLineId))
.findFirst()
.map(InvoiceAcctRule::getElementValueId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\acct\InvoiceAcct.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable ConfigDataResource getLocation() {
return this.location;
}
/**
* Return the replacement property that should be used instead or {@code null} if not
* replacement is available.
* @return the replacement property name
*/
public @Nullable ConfigurationPropertyName getReplacement() {
return this.replacement;
}
/**
* Throw an {@link InvalidConfigDataPropertyException} if the given
* {@link ConfigDataEnvironmentContributor} contains any invalid property.
* @param contributor the contributor to check
*/
static void throwIfPropertyFound(ConfigDataEnvironmentContributor contributor) {
ConfigurationPropertySource propertySource = contributor.getConfigurationPropertySource();
if (propertySource != null) {
ERRORS.forEach((name, replacement) -> {
ConfigurationProperty property = propertySource.getConfigurationProperty(name);
if (property != null) {
throw new InvalidConfigDataPropertyException(property, false, replacement,
contributor.getResource());
}
});
if (contributor.isFromProfileSpecificImport()
&& !contributor.hasConfigDataOption(ConfigData.Option.IGNORE_PROFILES)) {
PROFILE_SPECIFIC_ERRORS.forEach((name) -> {
ConfigurationProperty property = propertySource.getConfigurationProperty(name);
if (property != null) {
throw new InvalidConfigDataPropertyException(property, true, null, contributor.getResource());
}
});
}
}
}
private static String getMessage(ConfigurationProperty property, boolean profileSpecific,
@Nullable ConfigurationPropertyName replacement, @Nullable ConfigDataResource location) {
StringBuilder message = new StringBuilder("Property '");
message.append(property.getName());
if (location != null) {
|
message.append("' imported from location '");
message.append(location);
}
message.append("' is invalid");
if (profileSpecific) {
message.append(" in a profile specific resource");
}
if (replacement != null) {
message.append(" and should be replaced with '");
message.append(replacement);
message.append("'");
}
if (property.getOrigin() != null) {
message.append(" [origin: ");
message.append(property.getOrigin());
message.append("]");
}
return message.toString();
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\InvalidConfigDataPropertyException.java
| 2
|
请完成以下Java代码
|
public void makeDeliveryStopIfNeeded(@NonNull final I_C_DunningDoc dunningDoc)
{
final org.compiere.model.I_C_DunningLevel dunningLevel = dunningDoc.getC_DunningLevel();
if (!dunningLevel.isDeliveryStop())
{
return;
}
final IShipmentConstraintsBL shipmentConstraintsBL = Services.get(IShipmentConstraintsBL.class);
shipmentConstraintsBL.createConstraint(ShipmentConstraintCreateRequest.builder()
.billPartnerId(dunningDoc.getC_BPartner_ID())
.sourceDocRef(TableRecordReference.of(dunningDoc))
.deliveryStop(true)
.build());
}
@Override
public String getSummary(final I_C_Dunning_Candidate candidate)
{
if (candidate == null)
{
return null;
}
return "#" + candidate.getC_Dunning_Candidate_ID();
}
@Override
public boolean isExpired(final I_C_Dunning_Candidate candidate, final Timestamp dunningGraceDate)
{
Check.assumeNotNull(candidate, "candidate not null");
if (candidate.isProcessed())
{
// candidate already processed => not expired
return false;
}
if (dunningGraceDate == null)
|
{
// no dunning grace date => not expired
return false;
}
final Timestamp dunningDate = candidate.getDunningDate();
if (dunningDate.compareTo(dunningGraceDate) >= 0)
{
// DunningDate >= DunningGrace => candidate is perfectly valid. It's date is after dunningGrace date
return false;
}
// DunningDate < DunningGrace => candidate is no longer valid
return true;
}
@Override
public I_C_Dunning_Candidate getLastLevelCandidate(final List<I_C_Dunning_Candidate> candidates)
{
Check.errorIf(candidates.isEmpty(), "Error: No candidates selected.");
I_C_Dunning_Candidate result = candidates.get(0);
BigDecimal maxDaysAfterDue = result.getC_DunningLevel().getDaysAfterDue();
for (final I_C_Dunning_Candidate candidate : candidates)
{
if (maxDaysAfterDue.compareTo(candidate.getC_DunningLevel().getDaysAfterDue()) < 0)
{
result = candidate;
maxDaysAfterDue = candidate.getC_DunningLevel().getDaysAfterDue();
}
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningBL.java
| 1
|
请完成以下Java代码
|
public int getC_PaymentProcessor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_PaymentProcessor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Document No.
@param DocumentNo
Document sequence number of the document
*/
public void setDocumentNo (String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
/** Get Document No.
@return Document sequence number of the document
*/
public String getDocumentNo ()
{
return (String)get_Value(COLUMNNAME_DocumentNo);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getDocumentNo());
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** 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 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 Processing date.
@param ProcessingDate Processing date */
public void setProcessingDate (Timestamp ProcessingDate)
{
set_Value (COLUMNNAME_ProcessingDate, ProcessingDate);
}
/** Get Processing date.
@return Processing date */
public Timestamp getProcessingDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ProcessingDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentBatch.java
| 1
|
请完成以下Java代码
|
private void extendFlatrateTermIfAutoExtension(final I_C_Flatrate_Term term)
{
final I_C_Flatrate_Conditions conditions = term.getC_Flatrate_Conditions();
final I_C_Flatrate_Transition transition = conditions.getC_Flatrate_Transition();
if (transition != null
&& X_C_Flatrate_Transition.EXTENSIONTYPE_ExtendAll.equals(transition.getExtensionType())
&& transition.getC_Flatrate_Conditions_Next_ID() > 0)
{
final ContractExtendingRequest request = ContractExtendingRequest.builder()
.contract(term)
.forceExtend(true)
.forceComplete(true)
.nextTermStartDate(null)
.build();
// running in its own trx for backwards compatibility
trxManager.run(ITrx.TRXNAME_ThreadInherited, localTrxName_IGNORED -> flatrateBL.extendContractAndNotifyUser(request));
}
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE, ModelValidator.TIMING_AFTER_REACTIVATE })
public void handleReactivate(final I_C_Order order)
{
final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLines(order, I_C_OrderLine.class);
for (final I_C_OrderLine ol : orderLines)
{
if (ol.getC_Flatrate_Conditions_ID() <= 0)
{
logger.debug("Order line " + ol + " has no contract term assigned");
continue;
}
handleOrderLineReactivate(ol);
}
}
/**
* Make sure the orderLine still has processed='Y', even if the order is reactivated. <br>
* This was apparently added in task 03152.<br>
* I can guess that if an order line already has a C_Flatrate_Term, then we don't want that order line to be editable, because it could create inconsistencies with the term.
*/
private void handleOrderLineReactivate(final I_C_OrderLine ol)
{
logger.info("Setting order line's processed status " + ol + " back to Processed='Y'" + " as it references a contract term");
ol.setProcessed(true);
InterfaceWrapperHelper.save(ol);
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE })
public void updateCustomerRetention(final I_C_Order order)
{
|
final CustomerRetentionRepository customerRetentionRepo = SpringContextHolder.instance.getBean(CustomerRetentionRepository.class);
if (!order.isSOTrx())
{
// nothing to do
return;
}
final OrderId orderId = OrderId.ofRepoId(order.getC_Order_ID());
customerRetentionRepo.updateCustomerRetentionOnOrderComplete(orderId);
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = I_C_Order.COLUMNNAME_DatePromised)
public void updateOrderLineFromContract(final I_C_Order order)
{
orderDAO.retrieveOrderLines(order)
.stream()
.map(ol -> InterfaceWrapperHelper.create(ol, de.metas.contracts.order.model.I_C_OrderLine.class))
.filter(subscriptionBL::isSubscription)
.forEach(orderLineBL::updatePrices);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Order.java
| 1
|
请完成以下Java代码
|
private void onRecordAndChildrenCopied(final I_C_OrderLine toOrderLine, final I_C_OrderLine fromOrderLine)
{
ClonedOrderLinesInfo.getOrCreate(getTargetOrder())
.addOriginalToClonedOrderLineMapping(
OrderLineId.ofRepoId(fromOrderLine.getC_OrderLine_ID()),
OrderLineId.ofRepoId(toOrderLine.getC_OrderLine_ID()));
}
private I_C_Order getTargetOrder() {return Check.assumeNotNull(getParentModel(I_C_Order.class), "target order is not null");}
private int getOrCloneOrderCompensationGroup(final int orderCompensationGroupId)
{
if (orderCompensationGroupId <= 0)
{
return -1;
}
final I_C_Order toOrder = getTargetOrder();
Map<Integer, Integer> orderCompensationGroupIdsMap = InterfaceWrapperHelper.getDynAttribute(toOrder, DYNATTR_OrderCompensationGroupIdsMap);
if (orderCompensationGroupIdsMap == null)
{
orderCompensationGroupIdsMap = new HashMap<>();
InterfaceWrapperHelper.setDynAttribute(toOrder, DYNATTR_OrderCompensationGroupIdsMap, orderCompensationGroupIdsMap);
}
final int toOrderId = toOrder.getC_Order_ID();
|
final int orderCompensationGroupIdNew = orderCompensationGroupIdsMap.computeIfAbsent(orderCompensationGroupId, k -> cloneOrderCompensationGroup(orderCompensationGroupId, toOrderId));
return orderCompensationGroupIdNew;
}
private static int cloneOrderCompensationGroup(final int orderCompensationGroupId, final int toOrderId)
{
final I_C_Order_CompensationGroup orderCompensationGroup = load(orderCompensationGroupId, I_C_Order_CompensationGroup.class);
final I_C_Order_CompensationGroup orderCompensationGroupNew = newInstance(I_C_Order_CompensationGroup.class);
InterfaceWrapperHelper.copyValues(orderCompensationGroup, orderCompensationGroupNew);
orderCompensationGroupNew.setC_Order_ID(toOrderId);
orderCompensationGroupNew.setPP_Product_BOM_ID(-1); // don't copy the Quotation BOM; another one has to be created
InterfaceWrapperHelper.save(orderCompensationGroupNew);
return orderCompensationGroupNew.getC_Order_CompensationGroup_ID();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\copy\C_OrderLine_CopyRecordSupport.java
| 1
|
请完成以下Java代码
|
public void setAD_WF_Responsible_ID (int AD_WF_Responsible_ID)
{
if (AD_WF_Responsible_ID < 1)
set_Value (COLUMNNAME_AD_WF_Responsible_ID, null);
else
set_Value (COLUMNNAME_AD_WF_Responsible_ID, Integer.valueOf(AD_WF_Responsible_ID));
}
/** Get Workflow - Verantwortlicher.
@return Verantwortlicher für die Ausführung des Workflow
*/
@Override
public int getAD_WF_Responsible_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Responsible_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Workflow - Verantwortlicher (text).
@param AD_WF_Responsible_Name Workflow - Verantwortlicher (text) */
@Override
public void setAD_WF_Responsible_Name (java.lang.String AD_WF_Responsible_Name)
{
set_Value (COLUMNNAME_AD_WF_Responsible_Name, AD_WF_Responsible_Name);
}
/** Get Workflow - Verantwortlicher (text).
@return Workflow - Verantwortlicher (text) */
@Override
public java.lang.String getAD_WF_Responsible_Name ()
{
return (java.lang.String)get_Value(COLUMNNAME_AD_WF_Responsible_Name);
}
/** Set Document Responsible.
@param C_Doc_Responsible_ID Document Responsible */
@Override
public void setC_Doc_Responsible_ID (int C_Doc_Responsible_ID)
{
if (C_Doc_Responsible_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, Integer.valueOf(C_Doc_Responsible_ID));
}
/** Get Document Responsible.
@return Document Responsible */
@Override
public int getC_Doc_Responsible_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Doc_Responsible_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\workflow\model\X_C_Doc_Responsible.java
| 1
|
请完成以下Java代码
|
private @Nullable Object resolveSecurityContextFromAnnotation(MethodParameter parameter,
CurrentSecurityContext annotation, SecurityContext securityContext) {
Object securityContextResult = securityContext;
String expressionToParse = annotation.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(securityContext);
context.setVariable("this", securityContext);
// https://github.com/spring-projects/spring-framework/issues/35371
if (this.beanResolver != null) {
context.setBeanResolver(this.beanResolver);
}
Expression expression = this.parser.parseExpression(expressionToParse);
securityContextResult = expression.getValue(context);
}
if (securityContextResult != null
&& !parameter.getParameterType().isAssignableFrom(securityContextResult.getClass())) {
if (annotation.errorOnInvalidType()) {
throw new ClassCastException(
securityContextResult + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return securityContextResult;
}
|
/**
* Obtain the specified {@link Annotation} on the specified {@link MethodParameter}.
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private @Nullable CurrentSecurityContext findMethodAnnotation(MethodParameter parameter) {
if (this.useAnnotationTemplate) {
return this.scanner.scan(parameter.getParameter());
}
CurrentSecurityContext annotation = parameter.getParameterAnnotation(this.annotationType);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType);
if (annotation != null) {
return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize();
}
}
return null;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\method\annotation\CurrentSecurityContextArgumentResolver.java
| 1
|
请完成以下Java代码
|
public void setSourceElement(BaseElement sourceElement) {
this.sourceElement = sourceElement;
}
public String getTargetRef() {
return targetRef;
}
public void setTargetRef(String targetRef) {
this.targetRef = targetRef;
}
public BaseElement getTargetElement() {
return targetElement;
}
public void setTargetElement(BaseElement targetElement) {
this.targetElement = targetElement;
}
public String getTransitionEvent() {
return transitionEvent;
}
|
public void setTransitionEvent(String transitionEvent) {
this.transitionEvent = transitionEvent;
}
@Override
public Association clone() {
Association clone = new Association();
clone.setValues(this);
return clone;
}
public void setValues(Association otherElement) {
super.setValues(otherElement);
setSourceRef(otherElement.getSourceRef());
setTargetRef(otherElement.getTargetRef());
setTransitionEvent(otherElement.getTransitionEvent());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Association.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Duration getStep() {
return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
public Integer getNumThreads() {
return this.numThreads;
}
public void setNumThreads(Integer numThreads) {
this.numThreads = numThreads;
}
public Integer getBatchSize() {
return this.batchSize;
}
public void setBatchSize(Integer batchSize) {
this.batchSize = batchSize;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public Duration getMeterTimeToLive() {
return this.meterTimeToLive;
}
public void setMeterTimeToLive(Duration meterTimeToLive) {
this.meterTimeToLive = meterTimeToLive;
}
public boolean isLwcEnabled() {
return this.lwcEnabled;
|
}
public void setLwcEnabled(boolean lwcEnabled) {
this.lwcEnabled = lwcEnabled;
}
public Duration getLwcStep() {
return this.lwcStep;
}
public void setLwcStep(Duration lwcStep) {
this.lwcStep = lwcStep;
}
public boolean isLwcIgnorePublishStep() {
return this.lwcIgnorePublishStep;
}
public void setLwcIgnorePublishStep(boolean lwcIgnorePublishStep) {
this.lwcIgnorePublishStep = lwcIgnorePublishStep;
}
public Duration getConfigRefreshFrequency() {
return this.configRefreshFrequency;
}
public void setConfigRefreshFrequency(Duration configRefreshFrequency) {
this.configRefreshFrequency = configRefreshFrequency;
}
public Duration getConfigTimeToLive() {
return this.configTimeToLive;
}
public void setConfigTimeToLive(Duration configTimeToLive) {
this.configTimeToLive = configTimeToLive;
}
public String getConfigUri() {
return this.configUri;
}
public void setConfigUri(String configUri) {
this.configUri = configUri;
}
public String getEvalUri() {
return this.evalUri;
}
public void setEvalUri(String evalUri) {
this.evalUri = evalUri;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasProperties.java
| 2
|
请完成以下Java代码
|
public class ExternalTaskActivityBehavior extends AbstractBpmnActivityBehavior implements MigrationObserverBehavior {
protected ParameterValueProvider topicNameValueProvider;
protected ParameterValueProvider priorityValueProvider;
public ExternalTaskActivityBehavior(ParameterValueProvider topicName, ParameterValueProvider paramValueProvider) {
this.topicNameValueProvider = topicName;
this.priorityValueProvider = paramValueProvider;
}
@Override
public void execute(ActivityExecution execution) throws Exception {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
PriorityProvider<ExternalTaskActivityBehavior> provider = Context.getProcessEngineConfiguration().getExternalTaskPriorityProvider();
long priority = provider.determinePriority(executionEntity, this, null);
String topic = (String) topicNameValueProvider.getValue(executionEntity);
ExternalTaskEntity.createAndInsert(executionEntity, topic, priority);
}
@Override
public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception {
|
leave(execution);
}
public ParameterValueProvider getPriorityValueProvider() {
return priorityValueProvider;
}
@Override
public void migrateScope(ActivityExecution scopeExecution) {
}
@Override
public void onParseMigratingInstance(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) {
ExecutionEntity execution = migratingInstance.resolveRepresentativeExecution();
for (ExternalTaskEntity task : execution.getExternalTasks()) {
MigratingExternalTaskInstance migratingTask = new MigratingExternalTaskInstance(task, migratingInstance);
migratingInstance.addMigratingDependentInstance(migratingTask);
parseContext.consume(task);
parseContext.submit(migratingTask);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ExternalTaskActivityBehavior.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQtyDeliveredInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEntered (final @Nullable BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEnteredInBPartnerUOM (final @Nullable BigDecimal QtyEnteredInBPartnerUOM)
{
set_Value (COLUMNNAME_QtyEnteredInBPartnerUOM, QtyEnteredInBPartnerUOM);
}
@Override
public BigDecimal getQtyEnteredInBPartnerUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInBPartnerUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyItemCapacity (final @Nullable BigDecimal QtyItemCapacity)
{
set_Value (COLUMNNAME_QtyItemCapacity, QtyItemCapacity);
}
@Override
public BigDecimal getQtyItemCapacity()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
|
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered_Override (final @Nullable BigDecimal QtyOrdered_Override)
{
set_Value (COLUMNNAME_QtyOrdered_Override, QtyOrdered_Override);
}
@Override
public BigDecimal getQtyOrdered_Override()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered_Override);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUPC_CU (final @Nullable java.lang.String UPC_CU)
{
set_Value (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_Value (COLUMNNAME_UPC_TU, UPC_TU);
}
@Override
public java.lang.String getUPC_TU()
{
return get_ValueAsString(COLUMNNAME_UPC_TU);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_DesadvLine.java
| 1
|
请完成以下Java代码
|
public AmountAndCurrencyExchangeDetails3 getCntrValAmt() {
return cntrValAmt;
}
/**
* Sets the value of the cntrValAmt property.
*
* @param value
* allowed object is
* {@link AmountAndCurrencyExchangeDetails3 }
*
*/
public void setCntrValAmt(AmountAndCurrencyExchangeDetails3 value) {
this.cntrValAmt = value;
}
/**
* Gets the value of the anncdPstngAmt property.
*
* @return
* possible object is
* {@link AmountAndCurrencyExchangeDetails3 }
*
*/
public AmountAndCurrencyExchangeDetails3 getAnncdPstngAmt() {
return anncdPstngAmt;
}
/**
* Sets the value of the anncdPstngAmt property.
*
* @param value
* allowed object is
* {@link AmountAndCurrencyExchangeDetails3 }
*
*/
public void setAnncdPstngAmt(AmountAndCurrencyExchangeDetails3 value) {
this.anncdPstngAmt = value;
}
/**
* Gets the value of the prtryAmt property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prtryAmt property.
*
|
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrtryAmt().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AmountAndCurrencyExchangeDetails4 }
*
*
*/
public List<AmountAndCurrencyExchangeDetails4> getPrtryAmt() {
if (prtryAmt == null) {
prtryAmt = new ArrayList<AmountAndCurrencyExchangeDetails4>();
}
return this.prtryAmt;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\AmountAndCurrencyExchange3.java
| 1
|
请完成以下Java代码
|
public class FibonacciSeriesUtils {
public static int nthFibonacciTermRecursiveMethod(int n) {
if (n == 0 || n == 1) {
return n;
}
return nthFibonacciTermRecursiveMethod(n - 1) + nthFibonacciTermRecursiveMethod(n - 2);
}
public static int nthFibonacciTermIterativeMethod(int n) {
if (n == 0 || n == 1) {
return n;
}
int n0 = 0, n1 = 1;
int tempNthTerm;
|
for (int i = 2; i <= n; i++) {
tempNthTerm = n0 + n1;
n0 = n1;
n1 = tempNthTerm;
}
return n1;
}
public static int nthFibonacciTermUsingBinetsFormula(int n) {
final double squareRootOf5 = Math.sqrt(5);
final double phi = (1 + squareRootOf5)/2;
int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5);
return nthTerm;
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-3\src\main\java\com\baeldung\fibonacci\FibonacciSeriesUtils.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: sc-admin-client
eureka:
instance:
leaseRenewalIntervalInSeconds: 10
health-check-url-path: /actuator/health
client:
registryFetchIntervalSeconds: 5
service-url:
defaultZone: ${EUREKA_SERVICE_URL:http://localhost:8761}/eureka/
management:
|
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS
server:
port: 8762
|
repos\SpringBootLearning-master (1)\springboot-admin\sc-admin-client\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setM_Shipper_Mapping_Config_ID (final int M_Shipper_Mapping_Config_ID)
{
if (M_Shipper_Mapping_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_Mapping_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_Mapping_Config_ID, M_Shipper_Mapping_Config_ID);
}
@Override
public int getM_Shipper_Mapping_Config_ID()
{
|
return get_ValueAsInt(COLUMNNAME_M_Shipper_Mapping_Config_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper_Mapping_Config.java
| 1
|
请完成以下Java代码
|
public Thread createUserThread(final Runnable runnable, final String threadName)
{
final Thread thread;
if (threadName == null)
{
thread = new Thread(runnable);
}
else
{
thread = new Thread(runnable, threadName);
}
thread.setDaemon(true);
return thread;
}
@Override
public final void executeLongOperation(final Object component, final Runnable runnable)
{
invoke()
.setParentComponent(component)
.setLongOperation(true)
.setOnFail(OnFail.ThrowException) // backward compatibility
.invoke(runnable);
}
@Override
public void invokeLater(final int windowNo, final Runnable runnable)
{
invoke()
.setParentComponentByWindowNo(windowNo)
.setInvokeLater(true)
.setOnFail(OnFail.ThrowException) // backward compatibility
.invoke(runnable);
}
/**
* This method does nothing.
|
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}.
*/
@Deprecated
@Override
public void hideBusyDialog()
{
// nothing
}
/**
* This method does nothing.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#disableServerPush()}.
*/
@Deprecated
@Override
public void disableServerPush()
{
// nothing
}
/**
* This method throws an UnsupportedOperationException.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#infoNoWait(int, String)}.
* @throws UnsupportedOperationException
*/
@Deprecated
@Override
public void infoNoWait(int WindowNo, String AD_Message)
{
throw new UnsupportedOperationException("not implemented");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUIInstance.java
| 1
|
请完成以下Java代码
|
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int increaseSpeed(int increment) {
if (increment > 0) {
this.speed += increment;
} else {
System.out.println("Increment can't be negative.");
|
}
return this.speed;
}
public int decreaseSpeed(int decrement) {
if (decrement > 0 && decrement <= this.speed) {
this.speed -= decrement;
} else {
System.out.println("Decrement can't be negative or greater than current speed.");
}
return this.speed;
}
public void openDoors() {
// process to open the doors
}
@Override
public void honk() {
// produces car-specific honk
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-others\src\main\java\com\baeldung\oop\Car.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.