instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class PP_Product_Planning
{
@NonNull
private final MaturingConfigRepository maturingConfigRepo;
@NonNull
private final ProductBOMVersionsDAO bomVersionsDAO;
@Init
public void registerCallout()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@CalloutMethod(columnNames = { I_PP_Product_Planning.COLUMNNAME_IsMatured })
public void onIsMatured(final I_PP_Product_Planning productPlanningRecord)
{
if (productPlanningRecord.isMatured())
{
final List<MaturingConfigLine> configLines = maturingConfigRepo.getByMaturedProductId(ProductId.ofRepoIdOrNull(productPlanningRecord.getM_Product_ID()));
if (configLines.isEmpty() || configLines.size() > 1)
{
return;
}
final MaturingConfigLine line = configLines.get(0);
productPlanningRecord.setM_Maturing_Configuration_ID(MaturingConfigId.toRepoId(line.getMaturingConfigId()));
productPlanningRecord.setM_Maturing_Configuration_Line_ID(MaturingConfigLineId.toRepoId(line.getId()));
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW },
ifColumnsChanged = { I_PP_Product_Planning.COLUMNNAME_IsMatured })
public void validateMandatoryBOMVersionsAndWarehouseId(final I_PP_Product_Planning productPlanningRecord)
{
final ProductPlanning productPlanning = ProductPlanningDAO.fromRecord(productPlanningRecord);
if (!productPlanning.isMatured())
{
return; | }
if (productPlanning.getBomVersionsId() == null)
{
throw new FillMandatoryException(I_PP_Product_Planning.COLUMNNAME_PP_Product_BOMVersions_ID);
}
if (productPlanning.getWarehouseId() == null)
{
throw new FillMandatoryException(I_PP_Product_Planning.COLUMNNAME_M_Warehouse_ID);
}
}
@CalloutMethod(columnNames = I_PP_Product_Planning.COLUMNNAME_PP_Product_BOMVersions_ID)
public void onBOMVersionsChanged(@NonNull final I_PP_Product_Planning productPlanningRecord)
{
final ProductBOMVersionsId bomVersionsId = ProductBOMVersionsId.ofRepoIdOrNull(productPlanningRecord.getPP_Product_BOMVersions_ID());
if (bomVersionsId == null)
{
return;
}
final I_PP_Product_BOMVersions bomVersions = bomVersionsDAO.getBOMVersions(bomVersionsId);
final ProductId productId = ProductId.ofRepoId(bomVersions.getM_Product_ID());
productPlanningRecord.setM_Product_ID(productId.getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Product_Planning.java | 2 |
请完成以下Java代码 | public String getImplementation() {
return implementationAttribute.getValue(this);
}
public void setImplementation(String implementation) {
implementationAttribute.setValue(this, implementation);
}
public Message getMessage() {
return messageRefAttribute.getReferenceTargetElement(this);
}
public void setMessage(Message message) {
messageRefAttribute.setReferenceTargetElement(this, message);
}
public Operation getOperation() {
return operationRefAttribute.getReferenceTargetElement(this);
}
public void setOperation(Operation operation) {
operationRefAttribute.setReferenceTargetElement(this, operation);
}
/** camunda extensions */
public String getCamundaClass() {
return camundaClassAttribute.getValue(this);
}
public void setCamundaClass(String camundaClass) {
camundaClassAttribute.setValue(this, camundaClass);
}
public String getCamundaDelegateExpression() {
return camundaDelegateExpressionAttribute.getValue(this);
}
public void setCamundaDelegateExpression(String camundaExpression) {
camundaDelegateExpressionAttribute.setValue(this, camundaExpression);
} | public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
}
public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaResultVariable() {
return camundaResultVariableAttribute.getValue(this);
}
public void setCamundaResultVariable(String camundaResultVariable) {
camundaResultVariableAttribute.setValue(this, camundaResultVariable);
}
public String getCamundaTopic() {
return camundaTopicAttribute.getValue(this);
}
public void setCamundaTopic(String camundaTopic) {
camundaTopicAttribute.setValue(this, camundaTopic);
}
public String getCamundaType() {
return camundaTypeAttribute.getValue(this);
}
public void setCamundaType(String camundaType) {
camundaTypeAttribute.setValue(this, camundaType);
}
@Override
public String getCamundaTaskPriority() {
return camundaTaskPriorityAttribute.getValue(this);
}
@Override
public void setCamundaTaskPriority(String taskPriority) {
camundaTaskPriorityAttribute.setValue(this, taskPriority);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SendTaskImpl.java | 1 |
请完成以下Java代码 | public void calculate()
{
allocDate = null;
paymentInfo.setText(calculatePayment(paymentTable, multiCurrency.isSelected()));
invoiceInfo.setText(calculateInvoice(invoiceTable, multiCurrency.isSelected()));
// Set AllocationDate
if (allocDate != null)
{
dateField.setValue(allocDate);
}
// Set Allocation Currency
allocCurrencyLabel.setText(currencyPick.getDisplay());
// Difference
totalDiff = totalPay.subtract(totalInv);
differenceField.setText(format.format(totalDiff));
if (totalDiff.compareTo(new BigDecimal(0.0)) == 0)
{
allocateButton.setEnabled(true);
}
else
{ | allocateButton.setEnabled(false);
}
}
/**************************************************************************
* Save Data
*/
public void saveData()
{
try
{
Services.get(ITrxManager.class).runInNewTrx(trxName -> statusBar.setStatusLine(saveData(m_WindowNo, dateField.getValue(), paymentTable, invoiceTable, trxName)));
}
catch (Exception e)
{
ADialog.error(m_WindowNo, panel, "Error", e.getLocalizedMessage());
return;
}
} // saveData
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VAllocation.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_AttributeSearch[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Attribute Search.
@param M_AttributeSearch_ID
Common Search Attribute
*/
public void setM_AttributeSearch_ID (int M_AttributeSearch_ID)
{
if (M_AttributeSearch_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, Integer.valueOf(M_AttributeSearch_ID));
}
/** Get Attribute Search.
@return Common Search Attribute
*/
public int getM_AttributeSearch_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSearch_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSearch.java | 1 |
请完成以下Java代码 | private void recalculateStartingFromInvoice(@NonNull final RecalculateCommissionCriteria commissionCriteria,
final boolean salesRepAsCustomer)
{
final List<I_C_Invoice> invoices;
final String logMsg;
if (salesRepAsCustomer)
{
logMsg = "*** DEBUG: found {} Invoices while recalculating commission for criteria with C_BPartner_ID={} as *customer*; commissionCriteria={}";
invoices = invoiceDAO.retrieveSalesInvoiceByPartnerId(commissionCriteria.getSalesrepPartnerId(), commissionCriteria.getTargetInterval());
}
else
{
logMsg = "*** DEBUG: found {} Invoices while recalculating commission for criteria with C_BPartner_ID={} as *sales-rep*; commissionCriteria={}";
invoices = invoiceDAO.retrieveBySalesrepPartnerId(commissionCriteria.getSalesrepPartnerId(), commissionCriteria.getTargetInterval());
}
final int bpartnerSalesRepIdInt = RepoIdAwares.toRepoId(commissionCriteria.getSalesrepPartnerId());
final ILoggable loggableDebug = Loggables.withLogger(logger, Level.DEBUG);
loggableDebug.addLog(logMsg, invoices.size(), bpartnerSalesRepIdInt, commissionCriteria);
invoices.forEach(invoice -> {
try
{
if (salesRepAsCustomer && invoice.getC_BPartner_SalesRep_ID() != bpartnerSalesRepIdInt && bpartnerSalesRepIdInt != invoice.getC_BPartner_ID())
{
loggableDebug.addLog("*** DEBUG: C_Invoice_ID={} has C_BPartner_SalesRep_ID={}; -> fix it to C_BPartner_SalesRep_ID={}",
invoice.getC_Invoice_ID(), invoice.getC_BPartner_SalesRep_ID(), bpartnerSalesRepIdInt);
invoice.setC_BPartner_SalesRep_ID(bpartnerSalesRepIdInt);
InterfaceWrapperHelper.saveRecord(invoice);
} | invoiceFacadeService.syncInvoiceToCommissionInstance(invoice);
}
catch (final Exception e)
{
throw AdempiereException.wrapIfNeeded(e)
.appendParametersToMessage()
.setParameter("C_Invoice_ID", invoice.getC_Invoice_ID());
}
});
}
@Value
@Builder
private static class SalesRepRelatedBPTableInfo
{
@NonNull
AdTableId bPartnerTableId;
@NonNull
AdColumnId salesRepColumnId;
@NonNull
AdColumnId bPartnerSalesRepColumnId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\salesrep\process\C_Commission_Share_CreateMissingForSalesRep.java | 1 |
请完成以下Java代码 | public SetRemovalTimeToHistoricProcessInstancesBuilder clearedRemovalTime() {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
this.mode = Mode.CLEARED_REMOVAL_TIME;
return this;
}
@Override
public SetRemovalTimeToHistoricProcessInstancesBuilder hierarchical() {
isHierarchical = true;
return this;
}
@Override
public SetRemovalTimeToHistoricProcessInstancesBuilder updateInChunks() {
updateInChunks = true;
return this;
}
@Override
public SetRemovalTimeToHistoricProcessInstancesBuilder chunkSize(int chunkSize) {
if (chunkSize > ProcessSetRemovalTimeJobHandler.MAX_CHUNK_SIZE || chunkSize <= 0) {
throw new BadUserRequestException(String.format("The value for chunk size should be between 1 and %s",
ProcessSetRemovalTimeJobHandler.MAX_CHUNK_SIZE));
}
this.chunkSize = chunkSize;
return this;
}
@Override
public Batch executeAsync() {
return commandExecutor.execute(new SetRemovalTimeToHistoricProcessInstancesCmd(this));
}
public HistoricProcessInstanceQuery getQuery() {
return query;
} | public List<String> getIds() {
return ids;
}
public Date getRemovalTime() {
return removalTime;
}
public Mode getMode() {
return mode;
}
public boolean isHierarchical() {
return isHierarchical;
}
public boolean isUpdateInChunks() {
return updateInChunks;
}
public Integer getChunkSize() {
return chunkSize;
}
public static enum Mode
{
CALCULATED_REMOVAL_TIME,
ABSOLUTE_REMOVAL_TIME,
CLEARED_REMOVAL_TIME;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricProcessInstancesBuilderImpl.java | 1 |
请完成以下Java代码 | public class AliyunMessageProducer {
private static final String ACCESS_KEY = "LTAIcV7Ho2KS9a64";
private static final String SECRET_KEY = "3FWmAyWC99S3D8a3iVYzBZ0qiD4fOJ";
private static final String ONSAddr = "http://onsaddr-internet.aliyun.com/rocketmq/nsaddr4client-internet";
public static OrderProducer producer;
/**
* 获取消息的 Producer
* 设置为单例
* @param producerId producerId
* @return Producer
*/
public static OrderProducer getProducer(String producerId) {
if (producer == null) {
Properties properties = new Properties();
properties.put(PropertyKeyConst.ProducerId, producerId);
properties.put(PropertyKeyConst.AccessKey, ACCESS_KEY);
properties.put(PropertyKeyConst.SecretKey, SECRET_KEY);
properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
properties.put(PropertyKeyConst.ONSAddr,ONSAddr);
producer = ONSFactory.createOrderProducer(properties);
// 在发送消息前,必须调用start方法来启动Producer,只需调用一次即可。
producer.start();
}
return producer;
}
/**
* 发布消息
* @param producerId
* @param msg
* @return
*/ | public static SendResult sendMsg(String producerId,String sharding,Message msg) {
OrderProducer producer = getProducer(producerId); //你申请的producerId
SendResult sendResult = null;
try {
sendResult = producer.send(msg,sharding);
// 发送消息,只要不抛异常就是成功
if (sendResult != null) {
System.out.println(new Date() + " Send mq message success. Topic is:" + msg.getTopic() + " msgId is: " + sendResult.getMessageId());
}
}
catch (Exception e) {
// 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理
System.out.println(new Date() + " Send mq message failed. Topic is:" + msg.getTopic());
e.printStackTrace();
}
return sendResult;
}
} | repos\spring-boot-quick-master\quick-rocketmq\src\main\java\com\rocketmq\util\AliyunMessageProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult create(@RequestBody SmsFlashPromotion flashPromotion) {
int count = flashPromotionService.create(flashPromotion);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("编辑活动")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody SmsFlashPromotion flashPromotion) {
int count = flashPromotionService.update(id, flashPromotion);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("删除活动")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@PathVariable Long id) {
int count = flashPromotionService.delete(id);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("修改上下线状态")
@RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST)
@ResponseBody | public CommonResult update(@PathVariable Long id, Integer status) {
int count = flashPromotionService.updateStatus(id, status);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("获取活动详情")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<SmsFlashPromotion> getItem(@PathVariable Long id) {
SmsFlashPromotion flashPromotion = flashPromotionService.getItem(id);
return CommonResult.success(flashPromotion);
}
@ApiOperation("根据活动名称分页查询")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<SmsFlashPromotion>> getItem(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<SmsFlashPromotion> flashPromotionList = flashPromotionService.list(keyword, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(flashPromotionList));
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsFlashPromotionController.java | 2 |
请完成以下Java代码 | private static final String toString(final I_M_Attribute attribute)
{
if (attribute == null)
{
return "<NULL>";
}
else
{
return attribute.getName();
}
}
private static final ITranslatableString buildMsg(final I_M_Attribute attribute, final Object attributeSetObj)
{
final String attributeStr = toString(attribute);
return buildMsg(attributeStr, attributeSetObj);
}
private static final ITranslatableString buildMsg(final String attributeStr, final Object attributeSetObj)
{
final TranslatableStringBuilder builder = TranslatableStrings.builder();
builder.append("Attribute ");
if (attributeStr == null)
{
builder.append("<NULL>");
}
else
{
builder.append("'").append(attributeStr).append("'");
}
builder.append(" was not found"); | if (attributeSetObj != null)
{
builder.append(" for ").append(attributeSetObj.toString());
}
return builder.build();
}
public I_M_Attribute getM_Attribute()
{
return attribute;
}
public IAttributeSet getAttributeSet()
{
return attributeSet;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\exceptions\AttributeNotFoundException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SecurityWebFilterChain securityWebFilterChainPermitAll(ServerHttpSecurity http) {
return http.authorizeExchange((authorizeExchange) -> authorizeExchange.anyExchange().permitAll())
.csrf(ServerHttpSecurity.CsrfSpec::disable)
.build();
}
@Bean
@Profile("secure")
public SecurityWebFilterChain securityWebFilterChainSecure(ServerHttpSecurity http) {
return http
.authorizeExchange(
(authorizeExchange) -> authorizeExchange.pathMatchers(this.adminServer.path("/assets/**"))
.permitAll()
.pathMatchers("/actuator/health/**")
.permitAll()
.pathMatchers(this.adminServer.path("/login"))
.permitAll()
.anyExchange()
.authenticated())
.formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login"))
.authenticationSuccessHandler(loginSuccessHandler(this.adminServer.path("/")))) | .logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout"))
.logoutSuccessHandler(logoutSuccessHandler(this.adminServer.path("/login?logout"))))
.httpBasic(Customizer.withDefaults())
.csrf(ServerHttpSecurity.CsrfSpec::disable)
.build();
}
// The following two methods are only required when setting a custom base-path (see
// 'basepath' profile in application.yml)
private ServerLogoutSuccessHandler logoutSuccessHandler(String uri) {
RedirectServerLogoutSuccessHandler successHandler = new RedirectServerLogoutSuccessHandler();
successHandler.setLogoutSuccessUrl(URI.create(uri));
return successHandler;
}
private ServerAuthenticationSuccessHandler loginSuccessHandler(String uri) {
RedirectServerAuthenticationSuccessHandler successHandler = new RedirectServerAuthenticationSuccessHandler();
successHandler.setLocation(URI.create(uri));
return successHandler;
}
} | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-eureka\src\main\java\de\codecentric\boot\admin\SpringBootAdminEurekaApplication.java | 2 |
请完成以下Java代码 | public class EncryptUtil {
private static final Log LOG = LogFactory.getLog(EncryptUtil.class);
// 密码盐
public static final String PWDSALT = "PAY";
/**
* 私有构造方法,将该工具类设为单例模式.
*/
private EncryptUtil() {
}
/**
* 用MD5算法进行加密
*
* @param str
* 需要加密的字符串
* @return MD5加密后的结果
*/
public static String encodeMD5String(String str) {
return encode(str, "MD5");
}
/**
* 用SHA算法进行加密
*
* @param str
* 需要加密的字符串
* @return SHA加密后的结果
*/
public static String encodeSHAString(String str) {
return encode(str, "SHA");
}
/**
* 用base64算法进行加密
*
* @param str
* 需要加密的字符串
* @return base64加密后的结果
*/
public static String encodeBase64String(String str) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(str.getBytes());
}
/**
* 用base64算法进行解密 | *
* @param str
* 需要解密的字符串
* @return base64解密后的结果
* @throws IOException
*/
public static String decodeBase64String(String str) throws IOException {
BASE64Decoder encoder = new BASE64Decoder();
return new String(encoder.decodeBuffer(str));
}
private static String encode(String str, String method) {
MessageDigest mdInst = null;
// 把密文转换成十六进制的字符串形式
// 单线程用StringBuilder,速度快 多线程用stringbuffer,安全
StringBuilder dstr = new StringBuilder();
try {
// 获得MD5摘要算法的 MessageDigest对象
mdInst = MessageDigest.getInstance(method);
// 使用指定的字节更新摘要
mdInst.update(str.getBytes());
// 获得密文
byte[] md = mdInst.digest();
for (int i = 0; i < md.length; i++) {
int tmp = md[i];
if (tmp < 0) {
tmp += 256;
}
if (tmp < 16) {
dstr.append("0");
}
dstr.append(Integer.toHexString(tmp));
}
} catch (NoSuchAlgorithmException e) {
LOG.error(e);
}
return dstr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\EncryptUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("executeJobTrigger") Trigger executeJobTrigger) throws IOException, PropertyVetoException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
// this allows to update triggers in DB when updating settings in config file:
//用于quartz集群,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
factory.setOverwriteExistingJobs(true);
//用于quartz集群,加载quartz数据源
//factory.setDataSource(dataSource);
//QuartzScheduler 延时启动,应用启动完10秒后 QuartzScheduler 再启动
//factory.setStartupDelay(10);
//用于quartz集群,加载quartz数据源配置
factory.setAutoStartup(true);
factory.setQuartzProperties(quartzProperties());
factory.setApplicationContextSchedulerContextKey("applicationContext");
factory.setDataSource(createDataSource());
//注册触发器
Trigger[] triggers = {executeJobTrigger};
factory.setTriggers(triggers);
return factory;
}
/**
* 加载触发器
*
* 新建触发器进行job 的调度 例如 executeJobDetail
* @param jobDetail
* @return
*/
@Bean(name = "executeJobTrigger")
public CronTriggerFactoryBean executeJobTrigger(@Qualifier("executeJobDetail") JobDetail jobDetail) {
//每天凌晨3点执行
return cronTriggerFactoryBean(jobDetail, "0 1 0 * * ? ");
}
/**
* 加载job
*
* 新建job 类用来代理 | *
*
* @return
*/
@Bean
public JobDetailFactoryBean executeJobDetail() {
return createJobDetail(InvokingJobDetailFactory.class, GROUP_NAME, "executeJob");
}
/**
* 执行规则job工厂
*
* 配置job 类中需要定时执行的 方法 execute
* @param jobClass
* @param groupName
* @param targetObject
* @return
*/
private static JobDetailFactoryBean createJobDetail(Class<? extends Job> jobClass,
String groupName,
String targetObject) {
JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
factoryBean.setJobClass(jobClass);
factoryBean.setDurability(true);
factoryBean.setRequestsRecovery(true);
factoryBean.setGroup(groupName);
Map<String, String> map = new HashMap<>();
map.put("targetMethod", "execute");
map.put("targetObject", targetObject);
factoryBean.setJobDataAsMap(map);
return factoryBean;
}
} | repos\springBoot-master\springboot-Quartz\src\main\java\com\abel\quartz\config\QuartzConfig.java | 2 |
请完成以下Java代码 | public final class StringExpressionCompiler extends AbstractChunkBasedExpressionCompiler<String, IStringExpression>
{
public static final transient StringExpressionCompiler instance = new StringExpressionCompiler();
// NOTE to developer: make sure there are no variables here since we are using a shared instance
/**
* Escape '@' char, by replacing one @ with double @@
*/
public static String escape(final String str)
{
if (Check.isEmpty(str, true))
{
return str;
}
return str.replace(PARAMETER_TAG, PARAMETER_DOUBLE_TAG);
}
private StringExpressionCompiler()
{
super();
}
@Override
protected IStringExpression getNullExpression()
{
return IStringExpression.NULL;
}
@Override | protected IStringExpression createConstantExpression(final ExpressionContext context, final String expressionStr)
{
return ConstantStringExpression.of(expressionStr);
}
@Override
protected IStringExpression createSingleParamaterExpression(final ExpressionContext context, final String expressionStr, final CtxName parameter)
{
return new SingleParameterStringExpression(expressionStr, parameter);
}
@Override
protected IStringExpression createGeneralExpression(final ExpressionContext context, final String expressionStr, final List<Object> expressionChunks)
{
return new StringExpression(expressionStr, expressionChunks);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\StringExpressionCompiler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ObjectMapper jsonObjectMapper()
{
final ObjectMapper jsonObjectMapper = new ObjectMapper();
jsonObjectMapper.findAndRegisterModules();
return jsonObjectMapper;
}
@Bean
public MSV3PeerAuthToken authTokenString(@Value("${msv3server.peer.authToken:}") final String authTokenStringValue)
{
if (authTokenStringValue == null || authTokenStringValue.trim().isEmpty())
{
// a token is needed on the receiver side, even if it's not valid
return MSV3PeerAuthToken.TOKEN_NOT_SET;
}
return MSV3PeerAuthToken.of(authTokenStringValue);
}
@Override
public void afterPropertiesSet() | {
try
{
if (requestAllDataOnStartup)
{
msv3ServerPeerService.requestAllUpdates();
}
else if (requestConfigDataOnStartup)
{
msv3ServerPeerService.requestConfigUpdates();
}
}
catch (Exception ex)
{
logger.warn("Error while requesting ALL updates. Skipped.", ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\Application.java | 2 |
请完成以下Java代码 | public class SentryOnPart extends CmmnElement {
protected String name;
protected String sourceRef;
protected PlanItem source;
protected String standardEvent;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceRef() {
return sourceRef;
}
public void setSourceRef(String sourceRef) { | this.sourceRef = sourceRef;
}
public PlanItem getSource() {
return source;
}
public void setSource(PlanItem source) {
this.source = source;
}
public String getStandardEvent() {
return standardEvent;
}
public void setStandardEvent(String standardEvent) {
this.standardEvent = standardEvent;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\SentryOnPart.java | 1 |
请完成以下Java代码 | public class WidgetTypeInfoEntity extends AbstractWidgetTypeEntity<WidgetTypeInfo> {
public static final Map<String, String> SEARCH_COLUMNS_MAP = new HashMap<>();
static {
SEARCH_COLUMNS_MAP.put("createdTime", "created_time");
SEARCH_COLUMNS_MAP.put("tenantId", "tenant_id");
SEARCH_COLUMNS_MAP.put("widgetType", "widget_type");
}
@Column(name = ModelConstants.WIDGET_TYPE_IMAGE_PROPERTY)
private String image;
@Column(name = ModelConstants.WIDGET_TYPE_DESCRIPTION_PROPERTY)
private String description;
@Type(StringArrayType.class)
@Column(name = ModelConstants.WIDGET_TYPE_TAGS_PROPERTY, columnDefinition = "text[]")
private String[] tags;
@Column(name = ModelConstants.WIDGET_TYPE_WIDGET_TYPE_PROPERTY)
private String widgetType;
@Convert(converter = JsonConverter.class)
@Column(name = ModelConstants.WIDGET_BUNDLES_PROPERTY) | private JsonNode bundles;
public WidgetTypeInfoEntity() {
super();
}
@Override
public WidgetTypeInfo toData() {
BaseWidgetType baseWidgetType = super.toBaseWidgetType();
WidgetTypeInfo widgetTypeInfo = new WidgetTypeInfo(baseWidgetType);
widgetTypeInfo.setImage(image);
widgetTypeInfo.setDescription(description);
widgetTypeInfo.setTags(tags);
widgetTypeInfo.setWidgetType(widgetType);
widgetTypeInfo.setBundles(JacksonUtil.convertValue(bundles, new TypeReference<>() {}));
return widgetTypeInfo;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\WidgetTypeInfoEntity.java | 1 |
请完成以下Java代码 | public class SignedInfoType {
@XmlElement(name = "CanonicalizationMethod", required = true)
protected CanonicalizationMethodType canonicalizationMethod;
@XmlElement(name = "SignatureMethod", required = true)
protected SignatureMethodType signatureMethod;
@XmlElement(name = "Reference", required = true)
protected List<ReferenceType2> reference;
@XmlAttribute(name = "Id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
/**
* Gets the value of the canonicalizationMethod property.
*
* @return
* possible object is
* {@link CanonicalizationMethodType }
*
*/
public CanonicalizationMethodType getCanonicalizationMethod() {
return canonicalizationMethod;
}
/**
* Sets the value of the canonicalizationMethod property.
*
* @param value
* allowed object is
* {@link CanonicalizationMethodType }
*
*/
public void setCanonicalizationMethod(CanonicalizationMethodType value) {
this.canonicalizationMethod = value;
}
/**
* Gets the value of the signatureMethod property.
*
* @return
* possible object is
* {@link SignatureMethodType }
*
*/
public SignatureMethodType getSignatureMethod() {
return signatureMethod;
}
/**
* Sets the value of the signatureMethod property.
*
* @param value
* allowed object is
* {@link SignatureMethodType }
*
*/
public void setSignatureMethod(SignatureMethodType value) {
this.signatureMethod = value; | }
/**
* Gets the value of the reference 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 reference property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getReference().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ReferenceType2 }
*
*
*/
public List<ReferenceType2> getReference() {
if (reference == null) {
reference = new ArrayList<ReferenceType2>();
}
return this.reference;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\SignedInfoType.java | 1 |
请完成以下Java代码 | public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public org.compiere.model.I_M_Shipper_RoutingCode getM_Shipper_RoutingCode()
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_RoutingCode_ID, org.compiere.model.I_M_Shipper_RoutingCode.class);
}
@Override
public void setM_Shipper_RoutingCode(final org.compiere.model.I_M_Shipper_RoutingCode M_Shipper_RoutingCode)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_RoutingCode_ID, org.compiere.model.I_M_Shipper_RoutingCode.class, M_Shipper_RoutingCode);
}
@Override
public void setM_Shipper_RoutingCode_ID (final int M_Shipper_RoutingCode_ID)
{
if (M_Shipper_RoutingCode_ID < 1)
set_Value (COLUMNNAME_M_Shipper_RoutingCode_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_RoutingCode_ID, M_Shipper_RoutingCode_ID);
}
@Override
public int getM_Shipper_RoutingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_RoutingCode_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setPrevious_ID (final int Previous_ID)
{
if (Previous_ID < 1)
set_Value (COLUMNNAME_Previous_ID, null);
else
set_Value (COLUMNNAME_Previous_ID, Previous_ID);
}
@Override
public int getPrevious_ID()
{
return get_ValueAsInt(COLUMNNAME_Previous_ID);
}
@Override | public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No)
{
set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No);
}
@Override
public java.lang.String getSetup_Place_No()
{
return get_ValueAsString(COLUMNNAME_Setup_Place_No);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVisitorsAddress (final boolean VisitorsAddress)
{
set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress);
}
@Override
public boolean isVisitorsAddress()
{
return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OssFileServiceImpl extends ServiceImpl<OssFileMapper, OssFile> implements IOssFileService {
@Override
public void upload(MultipartFile multipartFile) throws Exception {
String fileName = multipartFile.getOriginalFilename();
fileName = CommonUtils.getFileName(fileName);
OssFile ossFile = new OssFile();
ossFile.setFileName(fileName);
String url = OssBootUtil.upload(multipartFile,"upload/test");
if(oConvertUtils.isEmpty(url)){
throw new JeecgBootException("上传文件失败! ");
}
// 返回阿里云原生域名前缀URL
ossFile.setUrl(OssBootUtil.getOriginalUrl(url));
this.save(ossFile); | }
@Override
public boolean delete(OssFile ossFile) {
try {
this.removeById(ossFile.getId());
OssBootUtil.deleteUrl(ossFile.getUrl());
}
catch (Exception ex) {
log.error(ex.getMessage(),ex);
return false;
}
return true;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\oss\service\impl\OssFileServiceImpl.java | 2 |
请完成以下Java代码 | public void run() {
long start = System.currentTimeMillis();
try {
// do trigger
XxlJobTrigger.trigger(jobId, triggerType, failRetryCount, executorShardingParam, executorParam, addressList);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
// check timeout-count-map
long minTim_now = System.currentTimeMillis()/60000;
if (minTim != minTim_now) {
minTim = minTim_now;
jobTimeoutCountMap.clear();
}
// incr timeout-count-map
long cost = System.currentTimeMillis()-start;
if (cost > 500) { // ob-timeout threshold 500ms
AtomicInteger timeoutCount = jobTimeoutCountMap.putIfAbsent(jobId, new AtomicInteger(1));
if (timeoutCount != null) {
timeoutCount.incrementAndGet();
}
}
}
}
});
}
// ---------------------- helper ----------------------
private static JobTriggerPoolHelper helper = new JobTriggerPoolHelper();
public static void toStart() {
helper.start();
} | public static void toStop() {
helper.stop();
}
/**
* @param jobId
* @param triggerType
* @param failRetryCount
* >=0: use this param
* <0: use param from job info config
* @param executorShardingParam
* @param executorParam
* null: use job param
* not null: cover job param
*/
public static void trigger(int jobId, TriggerTypeEnum triggerType, int failRetryCount, String executorShardingParam, String executorParam, String addressList) {
helper.addTrigger(jobId, triggerType, failRetryCount, executorShardingParam, executorParam, addressList);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\thread\JobTriggerPoolHelper.java | 1 |
请完成以下Java代码 | public void setSum(BigDecimal value) {
this.sum = value;
}
/**
* Gets the value of the ttlNetNtry property.
*
* @return
* possible object is
* {@link AmountAndDirection35 }
*
*/
public AmountAndDirection35 getTtlNetNtry() {
return ttlNetNtry;
}
/**
* Sets the value of the ttlNetNtry property.
*
* @param value
* allowed object is
* {@link AmountAndDirection35 }
*
*/
public void setTtlNetNtry(AmountAndDirection35 value) {
this.ttlNetNtry = value;
}
/**
* Gets the value of the fcstInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isFcstInd() {
return fcstInd;
}
/**
* Sets the value of the fcstInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setFcstInd(Boolean value) {
this.fcstInd = value;
}
/**
* Gets the value of the bkTxCd property.
*
* @return
* possible object is
* {@link BankTransactionCodeStructure4 }
*
*/
public BankTransactionCodeStructure4 getBkTxCd() {
return bkTxCd;
}
/**
* Sets the value of the bkTxCd property.
*
* @param value
* allowed object is
* {@link BankTransactionCodeStructure4 }
* | */
public void setBkTxCd(BankTransactionCodeStructure4 value) {
this.bkTxCd = value;
}
/**
* Gets the value of the avlbty 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 avlbty property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAvlbty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CashBalanceAvailability2 }
*
*
*/
public List<CashBalanceAvailability2> getAvlbty() {
if (avlbty == null) {
avlbty = new ArrayList<CashBalanceAvailability2>();
}
return this.avlbty;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TotalsPerBankTransactionCode3.java | 1 |
请完成以下Java代码 | public Optional<PaymentId> getByExtIdOrgId(
@NonNull final ExternalId externalId,
@NonNull final OrgId orgId)
{
return paymentDAO.getByExternalId(externalId, orgId)
.map(payment -> PaymentId.ofRepoId(payment.getC_Payment_ID()));
}
@Override
public CurrencyConversionContext extractCurrencyConversionContext(
@NonNull final I_C_Payment payment)
{
final PaymentCurrencyContext paymentCurrencyContext = PaymentCurrencyContext.ofPaymentRecord(payment);
CurrencyConversionContext conversionCtx = currencyConversionBL.createCurrencyConversionContext(
InstantAndOrgId.ofTimestamp(payment.getDateAcct(), OrgId.ofRepoId(payment.getAD_Org_ID())),
paymentCurrencyContext.getCurrencyConversionTypeId(),
ClientId.ofRepoId(payment.getAD_Client_ID()));
final FixedConversionRate fixedConversionRate = paymentCurrencyContext.toFixedConversionRateOrNull();
if (fixedConversionRate != null)
{
conversionCtx = conversionCtx.withFixedConversionRate(fixedConversionRate);
}
return conversionCtx;
}
@Override
public void validateDocTypeIsInSync(@NonNull final I_C_Payment payment)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(payment.getC_DocType_ID());
if (docTypeId == null)
{
return;
}
final I_C_DocType docType = docTypeBL.getById(docTypeId);
// Invoice
final I_C_Invoice invoice = InvoiceId.optionalOfRepoId(payment.getC_Invoice_ID())
.map(invoiceBL::getById)
.orElse(null);
if (invoice != null && invoice.isSOTrx() != docType.isSOTrx())
{
// task: 07564 the SOtrx flags don't match, but that's OK *if* the invoice i a credit memo (either for the vendor or customer side) | if (!invoiceBL.isCreditMemo(invoice))
{
throw new AdempiereException(MSG_PaymentDocTypeInvoiceInconsistent);
}
}
// globalqss - Allow prepayment to Purchase Orders
// Order Waiting Payment (can only be SO)
// if (C_Order_ID != 0 && dt != null && !dt.isSOTrx())
// return "PaymentDocTypeInvoiceInconsistent";
// Order
final OrderId orderId = OrderId.ofRepoIdOrNull(payment.getC_Order_ID());
if (orderId == null)
{
return;
}
final I_C_Order order = orderDAO.getById(orderId);
if (order.isSOTrx() != docType.isSOTrx())
{
throw new AdempiereException(MSG_PaymentDocTypeInvoiceInconsistent);
}
}
@Override
public void reversePaymentById(@NonNull final PaymentId paymentId)
{
final I_C_Payment payment = getById(paymentId);
payment.setDocAction(IDocument.ACTION_Reverse_Correct);
documentBL.processEx(payment, IDocument.ACTION_Reverse_Correct, IDocument.STATUS_Reversed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PaymentBL.java | 1 |
请完成以下Java代码 | public java.lang.String getCSVFieldQuote ()
{
return (java.lang.String)get_Value(COLUMNNAME_CSVFieldQuote);
}
/** Set DATEV Export Format.
@param DATEV_ExportFormat_ID DATEV Export Format */
@Override
public void setDATEV_ExportFormat_ID (int DATEV_ExportFormat_ID)
{
if (DATEV_ExportFormat_ID < 1)
set_ValueNoCheck (COLUMNNAME_DATEV_ExportFormat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DATEV_ExportFormat_ID, Integer.valueOf(DATEV_ExportFormat_ID));
}
/** Get DATEV Export Format.
@return DATEV Export Format */
@Override
public int getDATEV_ExportFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DATEV_ExportFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Decimal Separator.
@param DecimalSeparator Decimal Separator */
@Override
public void setDecimalSeparator (java.lang.String DecimalSeparator)
{
set_Value (COLUMNNAME_DecimalSeparator, DecimalSeparator);
}
/** Get Decimal Separator.
@return Decimal Separator */
@Override
public java.lang.String getDecimalSeparator ()
{
return (java.lang.String)get_Value(COLUMNNAME_DecimalSeparator);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name | Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Number Grouping Separator.
@param NumberGroupingSeparator Number Grouping Separator */
@Override
public void setNumberGroupingSeparator (java.lang.String NumberGroupingSeparator)
{
set_Value (COLUMNNAME_NumberGroupingSeparator, NumberGroupingSeparator);
}
/** Get Number Grouping Separator.
@return Number Grouping Separator */
@Override
public java.lang.String getNumberGroupingSeparator ()
{
return (java.lang.String)get_Value(COLUMNNAME_NumberGroupingSeparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportFormat.java | 1 |
请完成以下Java代码 | private static void throwError(String errorCode, String parameterName,
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication,
RegisteredClient registeredClient) {
throwError(errorCode, parameterName, ERROR_URI, authorizationCodeRequestAuthentication, registeredClient);
}
private static void throwError(String errorCode, String parameterName, String errorUri,
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication,
RegisteredClient registeredClient) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
throwError(error, parameterName, authorizationCodeRequestAuthentication, registeredClient);
}
private static void throwError(OAuth2Error error, String parameterName,
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication,
RegisteredClient registeredClient) {
String redirectUri = StringUtils.hasText(authorizationCodeRequestAuthentication.getRedirectUri())
? authorizationCodeRequestAuthentication.getRedirectUri()
: registeredClient.getRedirectUris().iterator().next();
if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_REQUEST) | && parameterName.equals(OAuth2ParameterNames.REDIRECT_URI)) {
redirectUri = null; // Prevent redirects
}
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken(
authorizationCodeRequestAuthentication.getAuthorizationUri(),
authorizationCodeRequestAuthentication.getClientId(),
(Authentication) authorizationCodeRequestAuthentication.getPrincipal(), redirectUri,
authorizationCodeRequestAuthentication.getState(), authorizationCodeRequestAuthentication.getScopes(),
authorizationCodeRequestAuthentication.getAdditionalParameters());
authorizationCodeRequestAuthenticationResult.setAuthenticated(true);
throw new OAuth2AuthorizationCodeRequestAuthenticationException(error,
authorizationCodeRequestAuthenticationResult);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationCodeRequestAuthenticationValidator.java | 1 |
请完成以下Java代码 | public void download(String bucketName, String key, Path downloadPath) {
s3Client.getObject(request ->
request
.bucket(bucketName)
.key(key),
ResponseTransformer.toFile(downloadPath));
}
public void copyObject(String sourceBucketName, String sourceKey,
String destinationBucketName, String destinationKey) {
s3Client.copyObject(request ->
request
.sourceBucket(sourceBucketName)
.sourceKey(sourceKey)
.destinationBucket(destinationBucketName)
.destinationKey(destinationKey));
}
public void delete(String bucketName, String key) {
s3Client.deleteObject(request ->
request
.bucket(bucketName) | .key(key));
}
public void delete(String bucketName, List<String> keys) {
List<ObjectIdentifier> objectsToDelete = keys
.stream()
.map(key -> ObjectIdentifier
.builder()
.key(key)
.build())
.toList();
s3Client.deleteObjects(request ->
request
.bucket(bucketName)
.delete(deleteRequest ->
deleteRequest
.objects(objectsToDelete)));
}
} | repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\S3ObjectOperationService.java | 1 |
请完成以下Java代码 | public final class UserVerificationRequirement implements Serializable {
@Serial
private static final long serialVersionUID = -2801001231345540040L;
/**
* The <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-userverificationrequirement-discouraged">discouraged</a>
* value indicates that the Relying Party does not want user verification employed
* during the operation (e.g., in the interest of minimizing disruption to the user
* interaction flow).
*/
public static final UserVerificationRequirement DISCOURAGED = new UserVerificationRequirement("discouraged");
/**
* The <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-userverificationrequirement-preferred">preferred</a>
* value indicates that the Relying Party prefers user verification for the operation
* if possible, but will not fail the operation if the response does not have the UV
* flag set.
*/
public static final UserVerificationRequirement PREFERRED = new UserVerificationRequirement("preferred");
/**
* The <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-userverificationrequirement-required">required</a>
* value indicates that the Relying Party requires user verification for the operation
* and will fail the overall ceremony if the response does not have the UV flag set. | */
public static final UserVerificationRequirement REQUIRED = new UserVerificationRequirement("required");
private final String value;
UserVerificationRequirement(String value) {
this.value = value;
}
/**
* Gets the value
* @return the value
*/
public String getValue() {
return this.value;
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\UserVerificationRequirement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | default @Nullable String getUsername() {
return null;
}
/**
* Login password of the server.
* @return the login password of the server or {@code null}
*/
default @Nullable String getPassword() {
return null;
}
/**
* Datacenter that is considered "local". Contact points should be from this
* datacenter.
* @return the datacenter that is considered "local"
*/
@Nullable String getLocalDatacenter();
/**
* SSL bundle to use. | * @return the SSL bundle to use
*/
default @Nullable SslBundle getSslBundle() {
return null;
}
/**
* A Cassandra node.
*
* @param host the hostname
* @param port the port
*/
record Node(String host, int port) {
}
} | repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraConnectionDetails.java | 2 |
请完成以下Java代码 | public class PersonForm {
@NotNull
@Size(min=2, max = 30)
private String name;
@NotNull
@Min(18)
private Integer age;
public String getName(){
return this.name = name;
}
public void setName(String name){
this.name = name;
} | public Integer getAge(){
return age;
}
public void setAge(Integer age){
this.age =age;
}
public String toString(){
return "Person (Name: " + this.name + ", Age: " + this.age + ")";
}
} | repos\SpringBoot-Projects-FullStack-master\Part-5 Spring Boot Web Application\SpringJSPCalculate\src\main\java\spring\jsp\PersonForm.java | 1 |
请完成以下Java代码 | public void handleMessage(final Message<?> message) throws MessagingException
{
final InboundEMail email = toInboundEMail(message);
emailService.onInboundEMailReceived(config, email);
}
private static InboundEMail toInboundEMail(final Message<?> message)
{
final MessageHeaders messageHeaders = message.getHeaders();
@SuppressWarnings("unchecked")
final MultiValueMap<String, Object> messageRawHeaders = messageHeaders.get(MailHeaders.RAW_HEADERS, MultiValueMap.class);
final MailContent mailContent = MailContentCollector.toMailContent(messageHeaders.get(InboundEMailHeaderAndContentMapper.CONTENT));
final String messageId = toMessageId(messageRawHeaders.getFirst("Message-ID"));
final String firstMessageIdReference = toMessageId(messageRawHeaders.getFirst("References"));
final String initialMessageId = CoalesceUtil.coalesce(firstMessageIdReference, messageId);
return InboundEMail.builder()
.from(messageHeaders.get(MailHeaders.FROM, String.class))
.to(ImmutableList.copyOf(messageHeaders.get(MailHeaders.TO, String[].class)))
.cc(ImmutableList.copyOf(messageHeaders.get(MailHeaders.CC, String[].class)))
.bcc(ImmutableList.copyOf(messageHeaders.get(MailHeaders.BCC, String[].class)))
.subject(messageHeaders.get(MailHeaders.SUBJECT, String.class))
.content(mailContent.getText())
.contentType(messageHeaders.get(MailHeaders.CONTENT_TYPE, String.class))
.receivedDate(toZonedDateTime(messageHeaders.get(MailHeaders.RECEIVED_DATE)))
.messageId(messageId)
.initialMessageId(initialMessageId)
.headers(convertMailHeadersToJson(messageRawHeaders))
.attachments(mailContent.getAttachments())
.build();
}
private static final String toMessageId(final Object messageIdObj)
{
if (messageIdObj == null)
{
return null;
}
return messageIdObj.toString();
}
private static ZonedDateTime toZonedDateTime(final Object dateObj)
{
return TimeUtil.asZonedDateTime(dateObj);
}
private static final ImmutableMap<String, Object> convertMailHeadersToJson(final MultiValueMap<String, Object> mailRawHeaders)
{
return mailRawHeaders.entrySet()
.stream()
.map(entry -> GuavaCollectors.entry(entry.getKey(), convertListToJson(entry.getValue())))
.filter(entry -> entry.getValue() != null)
.collect(GuavaCollectors.toImmutableMap());
} | private static final Object convertListToJson(final List<Object> values)
{
if (values == null || values.isEmpty())
{
return ImmutableList.of();
}
else if (values.size() == 1)
{
return convertValueToJson(values.get(0));
}
else
{
return values.stream()
.map(v -> convertValueToJson(v))
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
}
private static final Object convertValueToJson(final Object value)
{
if (value == null)
{
return null;
}
return value.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailMessageHandler.java | 1 |
请完成以下Java代码 | public List<HistoricVariableInstanceDto> queryHistoricVariableInstances(HistoricVariableInstanceQueryDto queryDto,
Integer firstResult, Integer maxResults, boolean deserializeObjectValues) {
queryDto.setObjectMapper(objectMapper);
HistoricVariableInstanceQuery query = queryDto.toQuery(processEngine);
query.disableBinaryFetching();
if (!deserializeObjectValues) {
query.disableCustomObjectDeserialization();
}
List<HistoricVariableInstance> matchingHistoricVariableInstances = QueryUtil.list(query, firstResult, maxResults);
List<HistoricVariableInstanceDto> historicVariableInstanceDtoResults = new ArrayList<HistoricVariableInstanceDto>();
for (HistoricVariableInstance historicVariableInstance : matchingHistoricVariableInstances) {
HistoricVariableInstanceDto resultHistoricVariableInstance = HistoricVariableInstanceDto.fromHistoricVariableInstance(historicVariableInstance);
historicVariableInstanceDtoResults.add(resultHistoricVariableInstance);
}
return historicVariableInstanceDtoResults;
} | @Override
public CountResultDto getHistoricVariableInstancesCount(UriInfo uriInfo) {
HistoricVariableInstanceQueryDto queryDto = new HistoricVariableInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricVariableInstancesCount(queryDto);
}
@Override
public CountResultDto queryHistoricVariableInstancesCount(HistoricVariableInstanceQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricVariableInstanceQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricVariableInstanceRestServiceImpl.java | 1 |
请完成以下Java代码 | public static String gensalt() {
return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS);
}
/**
* Check that a plaintext password matches a previously hashed one
* @param plaintext the plaintext password to verify
* @param hashed the previously-hashed password
* @return true if the passwords match, false otherwise
*/
public static boolean checkpw(String plaintext, String hashed) {
byte[] passwordb = plaintext.getBytes(StandardCharsets.UTF_8);
return equalsNoEarlyReturn(hashed, hashpwforcheck(passwordb, hashed));
}
/** | * Check that a password (as a byte array) matches a previously hashed one
* @param passwordb the password to verify, as a byte array
* @param hashed the previously-hashed password
* @return true if the passwords match, false otherwise
* @since 5.3
*/
public static boolean checkpw(byte[] passwordb, String hashed) {
return equalsNoEarlyReturn(hashed, hashpwforcheck(passwordb, hashed));
}
static boolean equalsNoEarlyReturn(String a, String b) {
return MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8), b.getBytes(StandardCharsets.UTF_8));
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\bcrypt\BCrypt.java | 1 |
请完成以下Java代码 | private final String createJavaName(final String name)
{
final char[] nameArray = name.toCharArray();
final StringBuilder nameClean = new StringBuilder();
boolean initCap = true;
for (int i = 0; i < nameArray.length; i++)
{
final char c = nameArray[i];
// metas: teo_sarca: begin
// replacing german umlauts with equivalent ascii
if (c == '\u00c4')
{
nameClean.append("Ae");
initCap = false;
}
else if (c == '\u00dc')
{
nameClean.append("Ue");
initCap = false;
}
else if (c == '\u00d6')
{
nameClean.append("Oe");
initCap = false;
}
else if (c == '\u00e4')
{
nameClean.append("ae");
initCap = false;
}
else if (c == '\u00fc')
{
nameClean.append("ue");
initCap = false;
}
else if (c == '\u00f6')
{
nameClean.append("oe");
initCap = false;
}
else if (c == '\u00df')
{
nameClean.append("ss");
initCap = false;
}
else
// metas: teo_sarca: end
if (Character.isJavaIdentifierPart(c))
{
if (initCap)
{
nameClean.append(Character.toUpperCase(c));
}
else
{
nameClean.append(c);
}
initCap = false;
}
else
{
if (c == '+')
{
nameClean.append("Plus");
}
else if (c == '-')
{
nameClean.append("_");
}
else if (c == '>')
{
if (name.indexOf('<') == -1)
{
nameClean.append("Gt");
}
}
else if (c == '<')
{
if (name.indexOf('>') == -1)
{
nameClean.append("Le");
}
}
else if (c == '!')
{ | nameClean.append("Not");
}
else if (c == '=')
{
nameClean.append("Eq");
}
else if (c == '~')
{
nameClean.append("Like");
}
initCap = true;
}
}
return nameClean.toString();
}
public ADRefListGenerator setColumnName(final String columnName)
{
_columnName = columnName;
return this;
}
private final String getColumnName()
{
Check.assumeNotEmpty(_columnName, "_columnName not empty");
return _columnName;
}
public ADRefListGenerator setListInfo(final ListInfo listInfo)
{
Check.assumeNotNull(listInfo, "listInfo not null");
_listInfo = listInfo;
return this;
}
private ListInfo getListInfo()
{
return _listInfo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\ad\persistence\modelgen\ADRefListGenerator.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getFinishOrderCount() {
return finishOrderCount;
}
public void setFinishOrderCount(Integer finishOrderCount) {
this.finishOrderCount = finishOrderCount;
}
public BigDecimal getFinishOrderAmount() {
return finishOrderAmount;
}
public void setFinishOrderAmount(BigDecimal finishOrderAmount) { | this.finishOrderAmount = finishOrderAmount;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", finishOrderCount=").append(finishOrderCount);
sb.append(", finishOrderAmount=").append(finishOrderAmount);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTag.java | 1 |
请完成以下Java代码 | private void dynamicDisplay()
{
final int fieldCount = model.getFieldCount();
for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++)
{
dynamicDisplay(fieldIndex);
}
}
/**
* Update field's UI properties: Displayed, Read-Write
*
* @param fieldIndex
*/
private void dynamicDisplay(final int fieldIndex)
{
final Properties ctx = model.getCtx();
final GridField gridField = model.getField(fieldIndex); // allways not null
final VEditor editor = fieldEditors.get(fieldIndex);
final VEditor editorTo = fieldEditorsTo.get(fieldIndex);
final JLabel separator = fieldSeparators.get(fieldIndex);
final JLabel label = fieldLabels.get(fieldIndex);
// Visibility
final boolean editorVisible = (editor != null) && gridField.isDisplayed(ctx);
final boolean editorToVisible = (editorTo != null) && editorVisible;
final boolean labelVisible = editorVisible || editorToVisible;
final boolean separatorVisible = editorVisible || editorToVisible;
// Read-Only/Read-Write
final boolean editorRW = editorVisible && gridField.isEditablePara(ctx);
final boolean editorToRW = editorToVisible && editorRW;
// Update fields
if (label != null)
{
label.setVisible(labelVisible);
}
if (editor != null)
{
editor.setVisible(editorVisible);
editor.setReadWrite(editorRW);
}
if (separator != null)
{
separator.setVisible(separatorVisible);
}
if (editorTo != null)
{
editorTo.setVisible(editorToVisible);
editorTo.setReadWrite(editorToRW);
}
}
public List<ProcessInfoParameter> createParameters()
{
//
// Make sure all editor values are pushed back to model (GridFields)
for (final VEditor editor : fieldEditorsAll)
{
final GridField gridField = editor.getField();
if (gridField == null)
{
// guard agaist null, shall not happen
continue;
} | final Object value = editor.getValue();
model.setFieldValue(gridField, value);
}
//
// Ask the model to create the parameters
return model.createProcessInfoParameters();
}
/**
* #782 Request focus on the first process parameter (if possible)
*/
public void focusFirstParameter()
{
if (fieldEditors.isEmpty())
{
// there are no parameters in this process. Nothing to focus
return;
}
for (final VEditor fieldEditor : fieldEditors)
{
final boolean focusGained = getComponent(fieldEditor).requestFocusInWindow();
if (focusGained)
{
return;
}
}
}
} // ProcessParameterPanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessParametersPanel.java | 1 |
请完成以下Java代码 | public void setDateAcct (Timestamp DateAcct)
{
set_ValueNoCheck (COLUMNNAME_DateAcct, DateAcct);
}
/** Get Account Date.
@return Accounting Date
*/
public Timestamp getDateAcct ()
{
return (Timestamp)get_Value(COLUMNNAME_DateAcct);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_ValueNoCheck (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
public I_Fact_Acct getFact_Acct() throws RuntimeException
{
return (I_Fact_Acct)MTable.get(getCtx(), I_Fact_Acct.Table_Name)
.getPO(getFact_Acct_ID(), get_TrxName()); }
/** Set Accounting Fact.
@param Fact_Acct_ID Accounting Fact */
public void setFact_Acct_ID (int Fact_Acct_ID)
{
if (Fact_Acct_ID < 1)
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID));
}
/** Get Accounting Fact.
@return Accounting Fact */
public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Level no.
@param LevelNo Level no */
public void setLevelNo (int LevelNo)
{ | set_ValueNoCheck (COLUMNNAME_LevelNo, Integer.valueOf(LevelNo));
}
/** Get Level no.
@return Level no */
public int getLevelNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LevelNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_ReportStatement.java | 1 |
请完成以下Java代码 | public java.lang.String getPluFileLocalFolder()
{
return get_ValueAsString(COLUMNNAME_PluFileLocalFolder);
}
@Override
public void setProduct_BaseFolderName (final String Product_BaseFolderName)
{
set_Value (COLUMNNAME_Product_BaseFolderName, Product_BaseFolderName);
}
@Override
public String getProduct_BaseFolderName()
{
return get_ValueAsString(COLUMNNAME_Product_BaseFolderName);
}
@Override
public void setTCP_Host (final String TCP_Host)
{
set_Value (COLUMNNAME_TCP_Host, TCP_Host);
}
@Override
public String getTCP_Host()
{ | return get_ValueAsString(COLUMNNAME_TCP_Host);
}
@Override
public void setTCP_PortNumber (final int TCP_PortNumber)
{
set_Value (COLUMNNAME_TCP_PortNumber, TCP_PortNumber);
}
@Override
public int getTCP_PortNumber()
{
return get_ValueAsInt(COLUMNNAME_TCP_PortNumber);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl.java | 1 |
请完成以下Spring Boot application配置 | spring:
cloud:
stream:
default-binder: kafka # Specify kafka as the default binder
kafka:
binder:
brokers: ${KAFKA_BROKER}
bindings:
default:
content-type: application/json
processStockPrices-in-0:
destination: stock-prices-in
group: live-stock-consumers-x
processStockPrices-out-0:
destination: stock-prices-out
group: live-stock-consumers-y
producer:
useNativeEncoding: true
kafka:
consumer:
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
group-id: my-group
properties:
reactiveAutoCommit: true |
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
properties:
spring:
json:
trusted:
packages: '*'
clickhouse:
r2dbc:
url: r2dbc:clickhouse://localhost:8123/default | repos\tutorials-master\spring-reactive-modules\spring-reactive-kafka-stream-binder\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public Boolean getLookupValuesStale()
{
return lookupValuesStale;
}
public ReasonSupplier getLookupValuesStaleReason()
{
return lookupValuesStaleReason;
}
/* package */void setLookupValuesStale(final Boolean lookupValuesStale, final ReasonSupplier reason)
{
this.lookupValuesStale = lookupValuesStale;
lookupValuesStaleReason = reason;
logger.trace("collect {} lookupValuesStale: {} -- {}", fieldName, lookupValuesStale, lookupValuesStaleReason);
}
public DocumentValidStatus getValidStatus()
{
return validStatus;
}
/* package */void setValidStatus(final DocumentValidStatus validStatus)
{
this.validStatus = validStatus;
logger.trace("collect {} validStatus: {}", fieldName, validStatus);
}
/* package */ void mergeFrom(final DocumentFieldChange fromEvent)
{
if (fromEvent.valueSet)
{
valueSet = true;
value = fromEvent.value;
valueReason = fromEvent.valueReason;
}
//
if (fromEvent.readonly != null)
{
readonly = fromEvent.readonly;
readonlyReason = fromEvent.readonlyReason;
}
//
if (fromEvent.mandatory != null)
{
mandatory = fromEvent.mandatory;
mandatoryReason = fromEvent.mandatoryReason;
}
//
if (fromEvent.displayed != null)
{
displayed = fromEvent.displayed;
displayedReason = fromEvent.displayedReason;
}
//
if (fromEvent.lookupValuesStale != null)
{
lookupValuesStale = fromEvent.lookupValuesStale;
lookupValuesStaleReason = fromEvent.lookupValuesStaleReason;
}
if (fromEvent.validStatus != null)
{
validStatus = fromEvent.validStatus;
}
if(fromEvent.fieldWarning != null)
{
fieldWarning = fromEvent.fieldWarning;
}
putDebugProperties(fromEvent.debugProperties);
}
/* package */ void mergeFrom(final IDocumentFieldChangedEvent fromEvent)
{
if (fromEvent.isValueSet())
{
valueSet = true;
value = fromEvent.getValue();
valueReason = null; // N/A
} | }
public void putDebugProperty(final String name, final Object value)
{
if (debugProperties == null)
{
debugProperties = new LinkedHashMap<>();
}
debugProperties.put(name, value);
}
public void putDebugProperties(final Map<String, Object> debugProperties)
{
if (debugProperties == null || debugProperties.isEmpty())
{
return;
}
if (this.debugProperties == null)
{
this.debugProperties = new LinkedHashMap<>();
}
this.debugProperties.putAll(debugProperties);
}
public Map<String, Object> getDebugProperties()
{
return debugProperties == null ? ImmutableMap.of() : debugProperties;
}
public void setFieldWarning(@NonNull final DocumentFieldWarning fieldWarning)
{
this.fieldWarning = fieldWarning;
}
public DocumentFieldWarning getFieldWarning()
{
return fieldWarning;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldChange.java | 1 |
请完成以下Java代码 | default ITranslatableString getTranslatableMsgText(final AdMessageKey adMessage, final List<Object> msgParameters)
{
final Object[] msgParametersArr = msgParameters != null ? msgParameters.toArray() : new Object[] {};
return getTranslatableMsgText(adMessage, msgParametersArr);
}
@Deprecated
default ITranslatableString getTranslatableMsgText(final String adMessage, final List<Object> msgParameters)
{
return getTranslatableMsgText(AdMessageKey.of(adMessage), msgParameters);
}
default ITranslatableString getTranslatableMsgText(final boolean booleanValue)
{
return getTranslatableMsgText(booleanValue ? MSG_Yes : MSG_No);
}
/**
* Gets AD_Language/message map
*
* @param adLanguage language key
* @param prefix prefix used to match the AD_Messages (keys)
* @param removePrefix if true, the prefix will be cut out from the AD_Message keys that will be returned
* @return a map of "AD_Message" (might be with the prefix removed) to "translated message" pairs
*/
Map<String, String> getMsgMap(String adLanguage, String prefix, boolean removePrefix);
void cacheReset();
default AdMessagesTreeLoader.Builder messagesTree()
{ | return AdMessagesTreeLoader.builder()
.msgBL(this);
}
String getBaseLanguageMsg(@NonNull AdMessageKey adMessage, @Nullable Object... msgParameters);
Optional<AdMessageId> getIdByAdMessage(@NonNull AdMessageKey value);
boolean isMessageExists(AdMessageKey adMessage);
Optional<AdMessageKey> getAdMessageKeyById(AdMessageId adMessageId);
@Nullable
String getErrorCode(@NonNull final AdMessageKey messageKey);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\IMsgBL.java | 1 |
请完成以下Java代码 | public int getAD_WF_Node_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Node_ID);
}
@Override
public void setAD_WF_NodeNext_ID (final int AD_WF_NodeNext_ID)
{
if (AD_WF_NodeNext_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_NodeNext_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_NodeNext_ID, AD_WF_NodeNext_ID);
}
@Override
public int getAD_WF_NodeNext_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_NodeNext_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override | public void setIsStdUserWorkflow (final boolean IsStdUserWorkflow)
{
set_Value (COLUMNNAME_IsStdUserWorkflow, IsStdUserWorkflow);
}
@Override
public boolean isStdUserWorkflow()
{
return get_ValueAsBoolean(COLUMNNAME_IsStdUserWorkflow);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTransitionCode (final java.lang.String TransitionCode)
{
set_Value (COLUMNNAME_TransitionCode, TransitionCode);
}
@Override
public java.lang.String getTransitionCode()
{
return get_ValueAsString(COLUMNNAME_TransitionCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_NodeNext.java | 1 |
请完成以下Java代码 | public void setAD_Replication_ID (int AD_Replication_ID)
{
if (AD_Replication_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Replication_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Replication_ID, Integer.valueOf(AD_Replication_ID));
}
/** Get Replication.
@return Data Replication Target
*/
public int getAD_Replication_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Replication Run.
@param AD_Replication_Run_ID
Data Replication Run
*/
public void setAD_Replication_Run_ID (int AD_Replication_Run_ID)
{
if (AD_Replication_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, Integer.valueOf(AD_Replication_Run_ID));
}
/** Get Replication Run.
@return Data Replication Run
*/
public int getAD_Replication_Run_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_Run_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{ | return (String)get_Value(COLUMNNAME_Description);
}
/** Set Replicated.
@param IsReplicated
The data is successfully replicated
*/
public void setIsReplicated (boolean IsReplicated)
{
set_ValueNoCheck (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated));
}
/** Get Replicated.
@return The data is successfully replicated
*/
public boolean isReplicated ()
{
Object oo = get_Value(COLUMNNAME_IsReplicated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set 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_AD_Replication_Run.java | 1 |
请完成以下Java代码 | public void run() {
preRunCheck();
super.run();
String oldState = caseInstanceEntity.getState();
String newState = getNewState();
if (!Objects.equals(oldState, newState)) {
invokePreLifecycleListeners();
CaseInstanceLifeCycleListenerUtil.callLifecycleListeners(commandContext, caseInstanceEntity, caseInstanceEntity.getState(), newState);
invokePostLifecycleListeners();
caseInstanceEntity.setState(newState);
internalExecute();
}
}
/**
* Internal hook to be implemented to invoke any listeners BEFORE the lifecycle listeners are being invoked and before the new state is set
* on the case instance.
*/
protected void invokePreLifecycleListeners() {
}
/** | * Internal hook to be implemented to invoke any listeners AFTER the lifecycle listeners are being invoked and before the new state is set
* on the case instance.
*/
protected void invokePostLifecycleListeners() {
}
public void preRunCheck() {
// Meant to be overridden
}
public abstract String getNewState();
public abstract void internalExecute();
public abstract void changeStateForChildPlanItemInstance(PlanItemInstanceEntity planItemInstanceEntity);
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\AbstractChangeCaseInstanceStateOperation.java | 1 |
请完成以下Java代码 | public void setRelativePeriod (BigDecimal RelativePeriod)
{
set_Value (COLUMNNAME_RelativePeriod, RelativePeriod);
}
/** Get Relative Period.
@return Period offset (0 is current)
*/
public BigDecimal getRelativePeriod ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativePeriod);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
*/
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else
set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
}
/** Get User Element 1.
@return User defined accounting Element
*/
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0; | return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportColumn.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Payer type(BigDecimal type) {
this.type = type;
return this;
}
/**
* 0 = Unbekannt, 1 = gesetzlich, 2 = privat, 3 = Berufsgenossenschaft, 4 = Selbstzahler, 5 = Andere
* minimum: 0
* maximum: 5
* @return type
**/
@Schema(example = "1", description = "0 = Unbekannt, 1 = gesetzlich, 2 = privat, 3 = Berufsgenossenschaft, 4 = Selbstzahler, 5 = Andere")
public BigDecimal getType() {
return type;
}
public void setType(BigDecimal type) {
this.type = type;
}
public Payer ikNumber(String ikNumber) {
this.ikNumber = ikNumber;
return this;
}
/**
* Get ikNumber
* @return ikNumber
**/
@Schema(example = "108534160", description = "")
public String getIkNumber() {
return ikNumber;
}
public void setIkNumber(String ikNumber) {
this.ikNumber = ikNumber;
}
public Payer timestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return timestamp
**/
@Schema(description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Payer payer = (Payer) o;
return Objects.equals(this._id, payer._id) && | Objects.equals(this.name, payer.name) &&
Objects.equals(this.type, payer.type) &&
Objects.equals(this.ikNumber, payer.ikNumber) &&
Objects.equals(this.timestamp, payer.timestamp);
}
@Override
public int hashCode() {
return Objects.hash(_id, name, type, ikNumber, timestamp);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Payer {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" ikNumber: ").append(toIndentedString(ikNumber)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Payer.java | 2 |
请完成以下Java代码 | public String getSummary(final DocumentTableFields docFields)
{
return extractRecord(docFields).getDocumentNo();
}
@Override
public String getDocumentInfo(final DocumentTableFields docFields)
{
return extractRecord(docFields).getDocumentNo();
}
@Override
public int getDoc_User_ID(final DocumentTableFields docFields)
{
return extractRecord(docFields).getCreatedBy();
}
@Override
public LocalDate getDocumentDate(final DocumentTableFields docFields)
{
final I_SAP_GLJournal record = extractRecord(docFields);
return TimeUtil.asLocalDate(record.getDateDoc());
}
@Override
public int getC_Currency_ID(final DocumentTableFields docFields)
{
return extractRecord(docFields).getC_Currency_ID();
}
@Override
public BigDecimal getApprovalAmt(final DocumentTableFields docFields)
{
// copy-paste from MJournal.getApprovalAmt()
return extractRecord(docFields).getTotalDr();
}
@Override
public void approveIt(final DocumentTableFields docFields)
{
approveIt(extractRecord(docFields));
}
private void approveIt(final I_SAP_GLJournal glJournal)
{
glJournal.setIsApproved(true);
}
@Override
public String completeIt(final DocumentTableFields docFields) | {
final I_SAP_GLJournal glJournalRecord = extractRecord(docFields);
assertPeriodOpen(glJournalRecord);
glJournalService.updateWhileSaving(
glJournalRecord,
glJournal -> {
glJournal.assertHasLines();
glJournal.updateLineAcctAmounts(glJournalService.getCurrencyConverter());
glJournal.assertTotalsBalanced();
glJournal.setProcessed(true);
}
);
glJournalRecord.setDocAction(IDocument.ACTION_None);
return IDocument.STATUS_Completed;
}
private static void assertPeriodOpen(final I_SAP_GLJournal glJournalRecord)
{
MPeriod.testPeriodOpen(Env.getCtx(), glJournalRecord.getDateAcct(), glJournalRecord.getC_DocType_ID(), glJournalRecord.getAD_Org_ID());
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_SAP_GLJournal glJournalRecord = extractRecord(docFields);
assertPeriodOpen(glJournalRecord);
glJournalService.updateWhileSaving(
glJournalRecord,
glJournal -> glJournal.setProcessed(false)
);
factAcctDAO.deleteForDocumentModel(glJournalRecord);
glJournalRecord.setPosted(false);
glJournalRecord.setProcessed(false);
glJournalRecord.setDocAction(X_GL_Journal.DOCACTION_Complete);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\document\SAPGLJournalDocumentHandler.java | 1 |
请完成以下Java代码 | public static CandidateId ofRepoId(final int repoId)
{
if (repoId == NULL.repoId)
{
return NULL;
}
else if (repoId == UNSPECIFIED.repoId)
{
return UNSPECIFIED;
}
else
{
return new CandidateId(repoId);
}
}
public static CandidateId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(@Nullable final CandidateId candidateId)
{
return candidateId != null ? candidateId.getRepoId() : -1;
}
public static boolean isNull(@Nullable final CandidateId id)
{
return id == null || id.isNull();
}
private CandidateId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "MD_Candidate_ID");
}
@Override
@Deprecated
public String toString()
{
if (isNull())
{
return "NULL";
}
else if (isUnspecified())
{
return "UNSPECIFIED";
}
else
{
return String.valueOf(repoId);
}
}
@Override
@JsonValue
public int getRepoId()
{
if (isUnspecified())
{
throw Check.mkEx("Illegal call of getRepoId() on the unspecified CandidateId instance");
}
else if (isNull())
{ | return -1;
}
else
{
return repoId;
}
}
public boolean isNull()
{
return repoId == IdConstants.NULL_REPO_ID;
}
public boolean isUnspecified()
{
return repoId == IdConstants.UNSPECIFIED_REPO_ID;
}
public boolean isRegular()
{
return !isNull() && !isUnspecified();
}
public static boolean isRegularNonNull(@Nullable final CandidateId candidateId)
{
return candidateId != null && candidateId.isRegular();
}
public void assertRegular()
{
if (!isRegular())
{
throw new AdempiereException("Expected " + this + " to be a regular ID");
}
}
public static boolean equals(@Nullable CandidateId id1, @Nullable CandidateId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\CandidateId.java | 1 |
请完成以下Java代码 | public abstract class AbstractValueTypeImpl implements ValueType {
private static final long serialVersionUID = 1L;
protected String name;
public AbstractValueTypeImpl(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
public boolean isAbstract() {
return false;
}
public ValueType getParent() {
return null;
}
public boolean canConvertFromTypedValue(TypedValue typedValue) {
return false;
}
public TypedValue convertFromTypedValue(TypedValue typedValue) {
throw unsupportedConversion(typedValue.getType());
}
protected IllegalArgumentException unsupportedConversion(ValueType typeToConvertTo) {
return new IllegalArgumentException("The type " + getName() + " supports no conversion from type: " + typeToConvertTo.getName());
}
@Override
public int hashCode() { | final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.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;
AbstractValueTypeImpl other = (AbstractValueTypeImpl) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
protected Boolean isTransient(Map<String, Object> valueInfo) {
if (valueInfo != null && valueInfo.containsKey(VALUE_INFO_TRANSIENT)) {
Object isTransient = valueInfo.get(VALUE_INFO_TRANSIENT);
if (isTransient instanceof Boolean) {
return (Boolean) isTransient;
} else {
throw new IllegalArgumentException("The property 'transient' should have a value of type 'boolean'.");
}
}
return false;
}
} | repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\AbstractValueTypeImpl.java | 1 |
请完成以下Java代码 | private static final class InboundEMailAttachmentDataSource implements DataSource
{
private InboundEMailAttachment attachment;
private InboundEMailAttachmentDataSource(@NonNull final InboundEMailAttachment attachment)
{
this.attachment = attachment;
}
@Override
public String getName()
{
return attachment.getFilename();
}
@Override
public String getContentType()
{
return attachment.getContentType();
} | @Override
public InputStream getInputStream() throws IOException
{
return Files.newInputStream(attachment.getTempFile());
}
@Override
public OutputStream getOutputStream() throws IOException
{
throw new UnsupportedOperationException();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailRepository.java | 1 |
请完成以下Java代码 | private boolean isTokenExpired(String token) {
Date expiredDate = getExpiredDateFromToken(token);
return expiredDate.before(new Date());
}
/**
* 从token中获取过期时间
*/
private Date getExpiredDateFromToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims.getExpiration();
}
/**
* 根据用户信息生成token
*/
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);
}
/**
* 当原来的token没过期时是可以刷新的
*
* @param oldToken 带tokenHead的token
*/
public String refreshHeadToken(String oldToken) {
if(StrUtil.isEmpty(oldToken)){
return null;
}
String token = oldToken.substring(tokenHead.length());
if(StrUtil.isEmpty(token)){
return null;
}
//token校验不通过
Claims claims = getClaimsFromToken(token);
if(claims==null){
return null;
} | //如果token已经过期,不支持刷新
if(isTokenExpired(token)){
return null;
}
//如果token在30分钟之内刚刷新过,返回原token
if(tokenRefreshJustBefore(token,30*60)){
return token;
}else{
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
}
/**
* 判断token在指定时间内是否刚刚刷新过
* @param token 原token
* @param time 指定时间(秒)
*/
private boolean tokenRefreshJustBefore(String token, int time) {
Claims claims = getClaimsFromToken(token);
Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
Date refreshDate = new Date();
//刷新时间在创建时间的指定时间内
if(refreshDate.after(created)&&refreshDate.before(DateUtil.offsetSecond(created,time))){
return true;
}
return false;
}
} | repos\mall-master\mall-security\src\main\java\com\macro\mall\security\util\JwtTokenUtil.java | 1 |
请完成以下Java代码 | public void serialize(
ProcessVariablesMap<String, Object> processVariablesMap,
JsonGenerator gen,
SerializerProvider serializers
) throws IOException {
HashMap<String, ProcessVariableValue> map = new HashMap<>();
for (Map.Entry<String, Object> entry : processVariablesMap.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
map.put(name, buildProcessVariableValue(value));
}
gen.writeObject(map);
}
private ProcessVariableValue buildProcessVariableValue(Object value) {
ProcessVariableValue variableValue = null;
if (value != null) {
Class<?> entryValueClass = value.getClass();
String entryType = resolveEntryType(entryValueClass, value);
if (OBJECT_TYPE_KEY.equals(entryType)) { | value = new ObjectValue(value);
}
String entryValue = conversionService.convert(value, String.class);
variableValue = new ProcessVariableValue(entryType, entryValue);
}
return variableValue;
}
private String resolveEntryType(Class<?> clazz, Object value) {
Class<?> entryType;
if (isScalarType(clazz)) {
entryType = clazz;
} else {
entryType = getContainerType(clazz, value).orElse(ObjectValue.class);
}
return forClass(entryType);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessVariablesMapSerializer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | final class OidcBackChannelLogoutTokenValidator implements OAuth2TokenValidator<Jwt> {
private static final String LOGOUT_VALIDATION_URL = "https://openid.net/specs/openid-connect-backchannel-1_0.html#Validation";
private static final String BACK_CHANNEL_LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
private final String audience;
private final String issuer;
OidcBackChannelLogoutTokenValidator(ClientRegistration clientRegistration) {
this.audience = clientRegistration.getClientId();
String issuer = clientRegistration.getProviderDetails().getIssuerUri();
Assert.hasText(issuer, "Provider issuer cannot be null");
this.issuer = issuer;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
Collection<OAuth2Error> errors = new ArrayList<>();
LogoutTokenClaimAccessor logoutClaims = jwt::getClaims;
Map<String, Object> events = logoutClaims.getEvents();
if (events == null) {
errors.add(invalidLogoutToken("events claim must not be null"));
}
else if (events.get(BACK_CHANNEL_LOGOUT_EVENT) == null) {
errors.add(invalidLogoutToken("events claim map must contain \"" + BACK_CHANNEL_LOGOUT_EVENT + "\" key"));
}
String issuer = logoutClaims.getIssuer().toExternalForm();
if (issuer == null) {
errors.add(invalidLogoutToken("iss claim must not be null"));
}
else if (!this.issuer.equals(issuer)) {
errors.add(invalidLogoutToken(
"iss claim value must match `ClientRegistration#getProviderDetails#getIssuerUri`"));
}
List<String> audience = logoutClaims.getAudience();
if (audience == null) {
errors.add(invalidLogoutToken("aud claim must not be null"));
}
else if (!audience.contains(this.audience)) {
errors.add(invalidLogoutToken("aud claim value must include `ClientRegistration#getClientId`"));
}
Instant issuedAt = logoutClaims.getIssuedAt(); | if (issuedAt == null) {
errors.add(invalidLogoutToken("iat claim must not be null"));
}
String jwtId = logoutClaims.getId();
if (jwtId == null) {
errors.add(invalidLogoutToken("jti claim must not be null"));
}
if (logoutClaims.getSubject() == null && logoutClaims.getSessionId() == null) {
errors.add(invalidLogoutToken("sub and sid claims must not both be null"));
}
if (logoutClaims.getClaim("nonce") != null) {
errors.add(invalidLogoutToken("nonce claim must not be present"));
}
return OAuth2TokenValidatorResult.failure(errors);
}
private static OAuth2Error invalidLogoutToken(String description) {
return new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, description, LOGOUT_VALIDATION_URL);
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcBackChannelLogoutTokenValidator.java | 2 |
请完成以下Java代码 | public void setIsCashBank (final boolean IsCashBank)
{
set_Value (COLUMNNAME_IsCashBank, IsCashBank);
}
@Override
public boolean isCashBank()
{
return get_ValueAsBoolean(COLUMNNAME_IsCashBank);
}
@Override
public void setIsImportAsSingleSummaryLine (final boolean IsImportAsSingleSummaryLine)
{
set_Value (COLUMNNAME_IsImportAsSingleSummaryLine, IsImportAsSingleSummaryLine);
}
@Override
public boolean isImportAsSingleSummaryLine()
{
return get_ValueAsBoolean(COLUMNNAME_IsImportAsSingleSummaryLine);
}
@Override
public void setIsOwnBank (final boolean IsOwnBank)
{
set_Value (COLUMNNAME_IsOwnBank, IsOwnBank);
}
@Override
public boolean isOwnBank()
{
return get_ValueAsBoolean(COLUMNNAME_IsOwnBank);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name); | }
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setRoutingNo (final java.lang.String RoutingNo)
{
set_Value (COLUMNNAME_RoutingNo, RoutingNo);
}
@Override
public java.lang.String getRoutingNo()
{
return get_ValueAsString(COLUMNNAME_RoutingNo);
}
@Override
public void setSwiftCode (final @Nullable java.lang.String SwiftCode)
{
set_Value (COLUMNNAME_SwiftCode, SwiftCode);
}
@Override
public java.lang.String getSwiftCode()
{
return get_ValueAsString(COLUMNNAME_SwiftCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Bank.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Version
private Integer version;
private String productId;
private String description;
private String imageUrl;
private BigDecimal price;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public Integer getId() {
return id;
} | public void setId(Integer id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
} | repos\springbootwebapp-master\src\main\java\guru\springframework\domain\Product.java | 2 |
请完成以下Java代码 | public void close() {
if(mongoClient != null) {
mongoClient.close();
}
}
@Override
public boolean requiresLayout() {
return false;
}
public String getConnectionUrl() {
return connectionUrl;
}
public void setConnectionUrl(String connectionUrl) {
this.connectionUrl = connectionUrl;
} | public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
} | repos\SpringBoot-Learning-master\1.x\Chapter4-2-5\src\main\java\com\didispace\log\MongoAppender.java | 1 |
请完成以下Java代码 | public class DefinitionsParser implements BpmnXMLConstants {
protected static final List<ExtensionAttribute> defaultAttributes = Arrays.asList(
new ExtensionAttribute(TYPE_LANGUAGE_ATTRIBUTE),
new ExtensionAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE),
new ExtensionAttribute(TARGET_NAMESPACE_ATTRIBUTE),
new ExtensionAttribute(ATTRIBUTE_EXPORTER),
new ExtensionAttribute(ATTRIBUTE_EXPORTER_VERSION)
);
@SuppressWarnings("unchecked")
public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception {
model.setExporter(xtr.getAttributeValue(null, ATTRIBUTE_EXPORTER));
model.setExporterVersion(xtr.getAttributeValue(null, ATTRIBUTE_EXPORTER_VERSION));
model.setTargetNamespace(xtr.getAttributeValue(null, TARGET_NAMESPACE_ATTRIBUTE));
for (int i = 0; i < xtr.getNamespaceCount(); i++) {
String prefix = xtr.getNamespacePrefix(i);
if (StringUtils.isNotEmpty(prefix)) {
model.addNamespace(prefix, xtr.getNamespaceURI(i));
}
} | for (int i = 0; i < xtr.getAttributeCount(); i++) {
ExtensionAttribute extensionAttribute = new ExtensionAttribute();
extensionAttribute.setName(xtr.getAttributeLocalName(i));
extensionAttribute.setValue(xtr.getAttributeValue(i));
if (StringUtils.isNotEmpty(xtr.getAttributeNamespace(i))) {
extensionAttribute.setNamespace(xtr.getAttributeNamespace(i));
}
if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) {
extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i));
}
if (!BpmnXMLUtil.isBlacklisted(extensionAttribute, defaultAttributes)) {
model.addDefinitionsAttribute(extensionAttribute);
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\parser\DefinitionsParser.java | 1 |
请完成以下Java代码 | public class MGroup extends X_R_Group
{
/**
*
*/
private static final long serialVersionUID = 3218102715154328611L;
/**
* Get MGroup from Cache
* @param ctx context
* @param R_Group_ID id
* @return MGroup
*/
public static MGroup get (Properties ctx, int R_Group_ID)
{
Integer key = new Integer (R_Group_ID);
MGroup retValue = (MGroup) s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MGroup (ctx, R_Group_ID, null);
if (retValue.get_ID () != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/** Cache */
private static CCache<Integer,MGroup> s_cache = new CCache<Integer,MGroup>("R_Group", 20); | /**************************************************************************
* Standard Constructor
* @param ctx context
* @param R_Group_ID group
* @param trxName trx
*/
public MGroup (Properties ctx, int R_Group_ID, String trxName)
{
super (ctx, R_Group_ID, trxName);
} // MGroup
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MGroup (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MGroup
} // MGroup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MGroup.java | 1 |
请完成以下Java代码 | protected List<VariableInstance> queryVariablesInstancesByVariableScopeIds(Collection<String> variableNames, Collection<String> variableScopeIds) {
VariableInstanceQueryImpl query = (VariableInstanceQueryImpl) getProcessEngine().getRuntimeService()
.createVariableInstanceQuery()
.disableBinaryFetching()
.disableCustomObjectDeserialization()
.variableNameIn(variableNames.toArray(new String[0]))
.variableScopeIdIn(variableScopeIds.toArray(new String[0]));
// the number of results is capped at:
// #tasks * #variableNames * 5 (we have five variable scopes per task)
// this value may exceed the configured query pagination limit, so we make an unbounded query.
// As #tasks is bounded by the pagination limit, it will never load an unbounded number of variables.
return query.unlimitedList();
}
protected boolean isEntityOfClass(Object entity, Class<?> entityClass) {
return entityClass.isAssignableFrom(entity.getClass());
} | protected boolean isEmptyJson(String jsonString) {
return jsonString == null || jsonString.trim().isEmpty() || EMPTY_JSON_BODY.matcher(jsonString).matches();
}
protected InvalidRequestException filterNotFound(Exception cause) {
return new InvalidRequestException(Status.NOT_FOUND, cause, "Filter with id '" + resourceId + "' does not exist.");
}
protected InvalidRequestException invalidQuery(Exception cause) {
return new InvalidRequestException(Status.BAD_REQUEST, cause, "Filter cannot be extended by an invalid query");
}
protected InvalidRequestException unsupportedEntityClass(Object entity) {
return new InvalidRequestException(Status.BAD_REQUEST, "Entities of class '" + entity.getClass().getCanonicalName() + "' are currently not supported by filters.");
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\FilterResourceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ModelAttributeSetInstanceListenerInterceptor extends AbstractModelInterceptor
{
private static final Logger logger = LogManager.getLogger(ModelAttributeSetInstanceListenerInterceptor.class);
private final ImmutableListMultimap<String, IModelAttributeSetInstanceListener> listenersBySourceTableName;
public ModelAttributeSetInstanceListenerInterceptor(@NonNull final Optional<List<IModelAttributeSetInstanceListener>> listeners)
{
final List<IModelAttributeSetInstanceListener> listenersList = listeners.orElseGet(ImmutableList::of);
listenersBySourceTableName = Multimaps.index(listenersList, IModelAttributeSetInstanceListener::getSourceTableName);
logger.info("Registered {} listeners: {}", listenersList.size(), listenersBySourceTableName);
}
@Override
protected void onInit(final IModelValidationEngine engine, final org.compiere.model.I_AD_Client client)
{
listenersBySourceTableName.keySet()
.forEach(tableName -> engine.addModelChange(tableName, this));
}
@Override
public void onModelChange(final Object model, final ModelChangeType changeType)
{
if (changeType != ModelChangeType.BEFORE_NEW && changeType != ModelChangeType.BEFORE_CHANGE)
{
return;
}
// Skip updating the ASI if automatic ASI updating is disabled (08091)
if (IModelAttributeSetInstanceListener.DYNATTR_DisableASIUpdateOnModelChange.getValue(model, false))
{
return;
}
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
for (final IModelAttributeSetInstanceListener listener : listenersBySourceTableName.get(tableName))
{
if (changeType.isNew() || isValueChanged(model, listener.getSourceColumnNames()))
{
listener.modelChanged(model);
} | }
}
/**
* @return true if at least one of the given column names were changed.
*/
private static boolean isValueChanged(final Object model, final List<String> columnNames)
{
if (columnNames == IModelAttributeSetInstanceListener.ANY_SOURCE_COLUMN)
{
return true;
}
if (columnNames == null || columnNames.isEmpty())
{
return false;
}
for (final String columnName : columnNames)
{
if (InterfaceWrapperHelper.isValueChanged(model, columnName))
{
return true;
}
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\asi_aware\interceptor\ModelAttributeSetInstanceListenerInterceptor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class QtyToDeliverMap
{
public static final QtyToDeliverMap EMPTY = new QtyToDeliverMap(ImmutableMap.of());
@NonNull Map<ShipmentScheduleId, StockQtyAndUOMQty> map;
@Builder
@Jacksonized
private QtyToDeliverMap(@NonNull final Map<ShipmentScheduleId, StockQtyAndUOMQty> map)
{
this.map = ImmutableMap.copyOf(map);
}
public static QtyToDeliverMap ofMap(final Map<ShipmentScheduleId, StockQtyAndUOMQty> map)
{
return map.isEmpty() ? EMPTY : new QtyToDeliverMap(ImmutableMap.copyOf(map));
}
public static QtyToDeliverMap of(@NonNull final ShipmentScheduleId shipmentScheduleId, @NonNull StockQtyAndUOMQty qtyToDeliver)
{
return ofMap(ImmutableMap.of(shipmentScheduleId, qtyToDeliver));
}
@NonNull
public static QtyToDeliverMap fromJson(@Nullable final String json)
{
if (json == null || Check.isBlank(json))
{
return QtyToDeliverMap.EMPTY;
}
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(json, QtyToDeliverMap.class);
} | catch (JsonProcessingException e)
{
throw new AdempiereException("Failed deserializing " + QtyToDeliverMap.class.getSimpleName() + " from json: " + json, e);
}
}
public String toJsonString()
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(this);
}
catch (JsonProcessingException e)
{
throw new AdempiereException("Failed serializing " + this, e);
}
}
public boolean isEmpty() {return map.isEmpty();}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds() {return ImmutableSet.copyOf(map.keySet());}
@Nullable
public StockQtyAndUOMQty getQtyToDeliver(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return map.get(shipmentScheduleId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\QtyToDeliverMap.java | 2 |
请完成以下Java代码 | public List<Player> loadAllPlayersWrapping(String playersFile) throws IOException {
try {
throw new IOException();
} catch (IOException io) {
throw io;
}
}
public List<Player> loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException {
try {
throw new IOException();
} catch (IOException io) {
throw new PlayerLoadException(io);
}
}
public List<Player> loadAllPlayersThrowable(String playersFile) {
try {
throw new NullPointerException();
} catch ( Throwable t ) {
throw t;
}
}
class FewerExceptions extends Exceptions {
@Override
public List<Player> loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException
return null;
// overridden
}
}
public void throwAsGotoAntiPattern() throws MyException {
try {
// bunch of code
throw new MyException();
// second bunch of code
} catch ( MyException e ) {
// third bunch of code
} | }
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
try {
// ...
} catch (Exception e) {} // <== catch and swallow
return 0;
}
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
try {
// ...
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
try {
throw new IOException();
} catch (IOException e) {
throw new PlayerScoreException(e);
}
}
public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
int score = 0;
try {
throw new IOException();
} finally {
return score; // <== the IOException is dropped
}
}
private boolean isFilenameValid(String name) {
return false;
}
} | repos\tutorials-master\core-java-modules\core-java-exceptions\src\main\java\com\baeldung\exceptions\exceptionhandling\Exceptions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class CassandraHealthContributorConfigurations {
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(CqlSession.class)
static class CassandraDriverConfiguration
extends CompositeHealthContributorConfiguration<CassandraDriverHealthIndicator, CqlSession> {
CassandraDriverConfiguration() {
super(CassandraDriverHealthIndicator::new);
}
@Bean
@ConditionalOnMissingBean(name = { "cassandraHealthIndicator", "cassandraHealthContributor" })
HealthContributor cassandraHealthContributor(ConfigurableListableBeanFactory beanFactory) {
return createContributor(beanFactory, CqlSession.class);
}
} | @Configuration(proxyBeanMethods = false)
@ConditionalOnBean(CqlSession.class)
static class CassandraReactiveDriverConfiguration extends
CompositeReactiveHealthContributorConfiguration<CassandraDriverReactiveHealthIndicator, CqlSession> {
CassandraReactiveDriverConfiguration() {
super(CassandraDriverReactiveHealthIndicator::new);
}
@Bean
@ConditionalOnMissingBean(name = { "cassandraHealthIndicator", "cassandraHealthContributor" })
ReactiveHealthContributor cassandraHealthContributor(Map<String, CqlSession> sessions) {
return createContributor(sessions);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\health\CassandraHealthContributorConfigurations.java | 2 |
请完成以下Java代码 | protected void eventNotificationsCompleted(PvmExecutionImpl execution) {
super.eventNotificationsCompleted(execution);
TransitionImpl transition = execution.getTransition();
PvmActivity destination;
if (transition == null) { // this is null after async cont. -> transition is not stored in execution
destination = execution.getActivity();
} else {
destination = transition.getDestination();
}
execution.setTransition(null);
execution.setActivity(destination);
if (execution.isProcessInstanceStarting()) {
// only call this method if we are currently in the starting phase;
// if not, this may make an unnecessary request to fetch the process | // instance from the database
execution.setProcessInstanceStarting(false);
}
execution.dispatchDelayedEventsAndPerformOperation(ACTIVITY_EXECUTE);
}
public String getCanonicalName() {
return "transition-notifiy-listener-start";
}
@Override
public boolean shouldHandleFailureAsBpmnError() {
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationTransitionNotifyListenerStart.java | 1 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override | public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueName (final @Nullable java.lang.String ValueName)
{
set_ValueNoCheck (COLUMNNAME_ValueName, ValueName);
}
@Override
public java.lang.String getValueName()
{
return get_ValueAsString(COLUMNNAME_ValueName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_List.java | 1 |
请完成以下Java代码 | public void setBenchmarkDate (Timestamp BenchmarkDate)
{
set_Value (COLUMNNAME_BenchmarkDate, BenchmarkDate);
}
/** Get Date.
@return Benchmark Date
*/
public Timestamp getBenchmarkDate ()
{
return (Timestamp)get_Value(COLUMNNAME_BenchmarkDate);
}
/** Set Value.
@param BenchmarkValue
Benchmark Value
*/
public void setBenchmarkValue (BigDecimal BenchmarkValue)
{
set_Value (COLUMNNAME_BenchmarkValue, BenchmarkValue);
}
/** Get Value.
@return Benchmark Value
*/
public BigDecimal getBenchmarkValue ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_BenchmarkValue);
if (bd == null)
return Env.ZERO;
return bd;
}
/** 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 Benchmark Data.
@param PA_BenchmarkData_ID
Performance Benchmark Data Point
*/ | public void setPA_BenchmarkData_ID (int PA_BenchmarkData_ID)
{
if (PA_BenchmarkData_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_BenchmarkData_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_BenchmarkData_ID, Integer.valueOf(PA_BenchmarkData_ID));
}
/** Get Benchmark Data.
@return Performance Benchmark Data Point
*/
public int getPA_BenchmarkData_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_BenchmarkData_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Benchmark getPA_Benchmark() throws RuntimeException
{
return (I_PA_Benchmark)MTable.get(getCtx(), I_PA_Benchmark.Table_Name)
.getPO(getPA_Benchmark_ID(), get_TrxName()); }
/** Set Benchmark.
@param PA_Benchmark_ID
Performance Benchmark
*/
public void setPA_Benchmark_ID (int PA_Benchmark_ID)
{
if (PA_Benchmark_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID));
}
/** Get Benchmark.
@return Performance Benchmark
*/
public int getPA_Benchmark_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_BenchmarkData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean submit(Region region) {
Long cnt = baseMapper.selectCount(Wrappers.<Region>query().lambda().eq(Region::getCode, region.getCode()));
if (cnt > 0) {
return this.updateById(region);
}
// 设置祖区划编号
Region parent = baseMapper.selectById(region.getParentCode());
if (Func.isNotEmpty(parent) || Func.isNotEmpty(parent.getCode())) {
String ancestors = parent.getAncestors() + StringPool.COMMA + parent.getCode();
region.setAncestors(ancestors);
}
// 设置省、市、区、镇、村
Integer level = region.getLevel();
String code = region.getCode();
String name = region.getName();
if (level == PROVINCE_LEVEL) {
region.setProvinceCode(code);
region.setProvinceName(name);
} else if (level == CITY_LEVEL) {
region.setCityCode(code);
region.setCityName(name);
} else if (level == DISTRICT_LEVEL) {
region.setDistrictCode(code);
region.setDistrictName(name);
} else if (level == TOWN_LEVEL) {
region.setTownCode(code);
region.setTownName(name);
} else if (level == VILLAGE_LEVEL) {
region.setVillageCode(code);
region.setVillageName(name);
}
return this.save(region);
}
@Override | public boolean removeRegion(String id) {
Long cnt = baseMapper.selectCount(Wrappers.<Region>query().lambda().eq(Region::getParentCode, id));
if (cnt > 0) {
throw new ServiceException("请先删除子节点!");
}
return removeById(id);
}
@Override
public List<RegionVO> lazyList(String parentCode, Map<String, Object> param) {
return baseMapper.lazyList(parentCode, param);
}
@Override
public List<RegionVO> lazyTree(String parentCode, Map<String, Object> param) {
return baseMapper.lazyTree(parentCode, param);
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\RegionServiceImpl.java | 2 |
请完成以下Java代码 | public String toString() {
return this.value;
}
/**
* Factory method to create a new {@link WebServerNamespace} from a value. If the
* context is {@code null} or not a web server context then {@link #SERVER} is
* returned.
* @param context the application context
* @return the web server namespace
* @since 4.0.1
*/
public static WebServerNamespace from(@Nullable ApplicationContext context) {
if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) {
return SERVER;
}
return from(WebServerApplicationContext.getServerNamespace(context)); | }
/**
* Factory method to create a new {@link WebServerNamespace} from a value. If the
* value is empty or {@code null} then {@link #SERVER} is returned.
* @param value the namespace value or {@code null}
* @return the web server namespace
*/
public static WebServerNamespace from(@Nullable String value) {
if (StringUtils.hasText(value)) {
return new WebServerNamespace(value);
}
return SERVER;
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebServerNamespace.java | 1 |
请完成以下Java代码 | public AvailabilityInfoResultForWebui retrieveAvailableStock(@NonNull final AvailableToPromiseQuery query)
{
final AvailableToPromiseResult commonsAvailableStock = availableToPromiseRepository.retrieveAvailableStock(query);
final AvailabilityInfoResultForWebuiBuilder clientResultBuilder = AvailabilityInfoResultForWebui.builder();
final List<AvailableToPromiseResultGroup> commonsResultGroups = commonsAvailableStock.getResultGroups();
for (final AvailableToPromiseResultGroup commonsResultGroup : commonsResultGroups)
{
final AvailabilityInfoResultForWebui.Group clientResultGroup = createClientResultGroup(commonsResultGroup);
clientResultBuilder.group(clientResultGroup);
}
return clientResultBuilder.build();
}
private AvailabilityInfoResultForWebui.Group createClientResultGroup(@NonNull final AvailableToPromiseResultGroup commonsResultGroup)
{
try
{
return createClientResultGroup0(commonsResultGroup);
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e).appendParametersToMessage()
.setParameter("commonsResultGroup", commonsResultGroup);
}
}
private Quantity extractQuantity(final AvailableToPromiseResultGroup commonsResultGroup)
{ | final BigDecimal qty = commonsResultGroup.getQty();
final I_C_UOM uom = productsService.getStockUOM(commonsResultGroup.getProductId());
return Quantity.of(qty, uom);
}
private AvailabilityInfoResultForWebui.Group createClientResultGroup0(final AvailableToPromiseResultGroup commonsResultGroup)
{
final Quantity quantity = extractQuantity(commonsResultGroup);
final AttributesKey attributesKey = commonsResultGroup.getStorageAttributesKey();
final AvailabilityInfoResultForWebui.Group.Type type = extractGroupType(attributesKey);
final ImmutableAttributeSet attributes = AvailabilityInfoResultForWebui.Group.Type.ATTRIBUTE_SET.equals(type)
? AttributesKeys.toImmutableAttributeSet(attributesKey)
: ImmutableAttributeSet.EMPTY;
return AvailabilityInfoResultForWebui.Group.builder()
.productId(commonsResultGroup.getProductId())
.qty(quantity)
.type(type)
.attributes(attributes)
.build();
}
public Set<AttributesKeyPattern> getPredefinedStorageAttributeKeys()
{
return availableToPromiseRepository.getPredefinedStorageAttributeKeys();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\adapter\AvailableToPromiseAdapter.java | 1 |
请完成以下Java代码 | public class MigrationInstructionImpl implements MigrationInstruction {
protected String sourceActivityId;
protected String targetActivityId;
protected boolean updateEventTrigger = false;
public MigrationInstructionImpl(String sourceActivityId, String targetActivityId) {
this(sourceActivityId, targetActivityId, false);
}
public MigrationInstructionImpl(String sourceActivityId, String targetActivityId, boolean updateEventTrigger) {
this.sourceActivityId = sourceActivityId;
this.targetActivityId = targetActivityId;
this.updateEventTrigger = updateEventTrigger;
}
public String getSourceActivityId() {
return sourceActivityId;
} | public String getTargetActivityId() {
return targetActivityId;
}
public boolean isUpdateEventTrigger() {
return updateEventTrigger;
}
public void setUpdateEventTrigger(boolean updateEventTrigger) {
this.updateEventTrigger = updateEventTrigger;
}
public String toString() {
return "MigrationInstructionImpl{" +
"sourceActivityId='" + sourceActivityId + '\'' +
", targetActivityId='" + targetActivityId + '\'' +
", updateEventTrigger='" + updateEventTrigger + '\'' +
'}';
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\MigrationInstructionImpl.java | 1 |
请完成以下Java代码 | public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) {
parseConnectorElement(serviceTaskElement, scope, activity);
}
@Override
public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) {
Element messageEventDefinitionElement = endEventElement.element(BpmnParse.MESSAGE_EVENT_DEFINITION);
if (messageEventDefinitionElement != null) {
parseConnectorElement(messageEventDefinitionElement, scope, activity);
}
}
@Override
public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
Element messageEventDefinitionElement = intermediateEventElement.element(BpmnParse.MESSAGE_EVENT_DEFINITION);
if (messageEventDefinitionElement != null) {
parseConnectorElement(messageEventDefinitionElement, scope, activity);
}
}
@Override
public void parseBusinessRuleTask(Element businessRuleTaskElement, ScopeImpl scope, ActivityImpl activity) {
parseConnectorElement(businessRuleTaskElement, scope, activity);
}
@Override
public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) {
parseConnectorElement(sendTaskElement, scope, activity);
} | protected void parseConnectorElement(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) {
Element connectorDefinition = findCamundaExtensionElement(serviceTaskElement, "connector");
if (connectorDefinition != null) {
Element connectorIdElement = connectorDefinition.element("connectorId");
String connectorId = null;
if (connectorIdElement != null) {
connectorId = connectorIdElement.getText().trim();
}
if (connectorIdElement == null || connectorId.isEmpty()) {
throw new BpmnParseException("No 'id' defined for connector.", connectorDefinition);
}
IoMapping ioMapping = parseInputOutput(connectorDefinition);
activity.setActivityBehavior(new ServiceTaskConnectorActivityBehavior(connectorId, ioMapping));
}
}
} | repos\camunda-bpm-platform-master\engine-plugins\connect-plugin\src\main\java\org\camunda\connect\plugin\impl\ConnectorParseListener.java | 1 |
请完成以下Java代码 | default Set<HealthEndpointGroup> getAllWithAdditionalPath(WebServerNamespace namespace) {
Assert.notNull(namespace, "'namespace' must not be null");
Set<HealthEndpointGroup> filteredGroups = new LinkedHashSet<>();
getNames().stream()
.map(this::get)
.filter((group) -> group != null && group.getAdditionalPath() != null
&& group.getAdditionalPath().hasNamespace(namespace))
.forEach(filteredGroups::add);
return filteredGroups;
}
/**
* Factory method to create a {@link HealthEndpointGroups} instance.
* @param primary the primary group
* @param additional the additional groups
* @return a new {@link HealthEndpointGroups} instance
*/
static HealthEndpointGroups of(HealthEndpointGroup primary, Map<String, HealthEndpointGroup> additional) {
Assert.notNull(primary, "'primary' must not be null");
Assert.notNull(additional, "'additional' must not be null");
return new HealthEndpointGroups() {
@Override
public HealthEndpointGroup getPrimary() {
return primary; | }
@Override
public Set<String> getNames() {
return additional.keySet();
}
@Override
public @Nullable HealthEndpointGroup get(String name) {
return additional.get(name);
}
};
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\HealthEndpointGroups.java | 1 |
请完成以下Java代码 | public class TbDeleteRelationNode extends TbAbstractRelationActionNode<TbDeleteRelationNodeConfiguration> {
@Override
protected TbDeleteRelationNodeConfiguration loadEntityNodeActionConfig(TbNodeConfiguration configuration) throws TbNodeException {
var deleteRelationNodeConfiguration = TbNodeUtils.convert(configuration, TbDeleteRelationNodeConfiguration.class);
if (!deleteRelationNodeConfiguration.isDeleteForSingleEntity()) {
return deleteRelationNodeConfiguration;
}
checkIfConfigEntityTypeIsSupported(deleteRelationNodeConfiguration.getEntityType());
return deleteRelationNodeConfiguration;
}
@Override
protected boolean createEntityIfNotExists() {
return false;
}
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
ListenableFuture<Boolean> deleteResultFuture = config.isDeleteForSingleEntity() ?
Futures.transformAsync(getTargetEntityId(ctx, msg), targetEntityId ->
deleteRelationToSpecificEntity(ctx, msg, targetEntityId), MoreExecutors.directExecutor()) :
deleteRelationsByTypeAndDirection(ctx, msg, ctx.getDbCallbackExecutor());
withCallback(deleteResultFuture, deleted -> {
if (deleted) {
ctx.tellSuccess(msg);
return;
}
ctx.tellFailure(msg, new RuntimeException("Failed to delete relation(s) with originator!"));
},
t -> ctx.tellFailure(msg, t), MoreExecutors.directExecutor());
}
private ListenableFuture<Boolean> deleteRelationToSpecificEntity(TbContext ctx, TbMsg msg, EntityId targetEntityId) { | EntityId fromId;
EntityId toId;
if (EntitySearchDirection.FROM.equals(config.getDirection())) {
fromId = msg.getOriginator();
toId = targetEntityId;
} else {
toId = msg.getOriginator();
fromId = targetEntityId;
}
var relationType = processPattern(msg, config.getRelationType());
var tenantId = ctx.getTenantId();
var relationService = ctx.getRelationService();
return Futures.transformAsync(relationService.checkRelationAsync(tenantId, fromId, toId, relationType, RelationTypeGroup.COMMON),
relationExists -> {
if (relationExists) {
return relationService.deleteRelationAsync(tenantId, fromId, toId, relationType, RelationTypeGroup.COMMON);
}
return Futures.immediateFuture(true);
}, MoreExecutors.directExecutor());
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbDeleteRelationNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MSV3ServerRequestsRabbitMQListener
{
private static final Logger logger = LogManager.getLogger(MSV3ServerRequestsRabbitMQListener.class);
@Autowired
private UserAuthTokenService authService;
@Autowired
private MSV3CustomerConfigService customerConfigService;
@Autowired
private MSV3StockAvailabilityService stockAvailabilityService;
@RabbitListener(queues = RabbitMQConfig.QUEUENAME_MSV3ServerRequests)
public void onRequest(@Payload final MSV3ServerRequest request, @Header(MSV3PeerAuthToken.NAME) final MSV3PeerAuthToken authToken)
{
try
{
authService.run(authToken::getValueAsString, () -> process(request));
}
catch (final Exception ex)
{
logger.error("Failed processing: {}", request, ex); | }
}
private void process(final MSV3ServerRequest request)
{
if (request.isRequestAllUsers())
{
customerConfigService.publishAllConfig();
}
if (request.isRequestAllStockAvailabilities())
{
stockAvailabilityService.publishAll();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\listeners\MSV3ServerRequestsRabbitMQListener.java | 2 |
请完成以下Java代码 | public boolean isMutableValue(ObjectValue typedValue) {
return typedValue.isDeserialized();
}
// methods to be implemented by subclasses ////////////
/**
* Returns the type name for the deserialized object.
*
* @param deserializedObject. Guaranteed not to be null
* @return the type name fot the object.
*/
protected abstract String getTypeNameForDeserialized(Object deserializedObject);
/**
* Implementations must return a byte[] representation of the provided object.
* The object is guaranteed not to be null.
*
* @param deserializedObject the object to serialize
* @return the byte array value of the object
* @throws exception in case the object cannot be serialized
*/
protected abstract byte[] serializeToByteArray(Object deserializedObject) throws Exception;
protected Object deserializeFromByteArray(byte[] object, ValueFields valueFields) throws Exception {
String objectTypeName = readObjectNameFromFields(valueFields); | return deserializeFromByteArray(object, objectTypeName);
}
/**
* Deserialize the object from a byte array.
*
* @param object the object to deserialize
* @param objectTypeName the type name of the object to deserialize
* @return the deserialized object
* @throws exception in case the object cannot be deserialized
*/
protected abstract Object deserializeFromByteArray(byte[] object, String objectTypeName) throws Exception;
/**
* Return true if the serialization is text based. Return false otherwise
*
*/
protected abstract boolean isSerializationTextBased();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\AbstractObjectValueSerializer.java | 1 |
请完成以下Java代码 | public static QtyToDeliverMap of(@NonNull final ShipmentScheduleId shipmentScheduleId, @NonNull StockQtyAndUOMQty qtyToDeliver)
{
return ofMap(ImmutableMap.of(shipmentScheduleId, qtyToDeliver));
}
@NonNull
public static QtyToDeliverMap fromJson(@Nullable final String json)
{
if (json == null || Check.isBlank(json))
{
return QtyToDeliverMap.EMPTY;
}
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(json, QtyToDeliverMap.class);
}
catch (JsonProcessingException e)
{
throw new AdempiereException("Failed deserializing " + QtyToDeliverMap.class.getSimpleName() + " from json: " + json, e);
}
} | public String toJsonString()
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(this);
}
catch (JsonProcessingException e)
{
throw new AdempiereException("Failed serializing " + this, e);
}
}
public boolean isEmpty() {return map.isEmpty();}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds() {return ImmutableSet.copyOf(map.keySet());}
@Nullable
public StockQtyAndUOMQty getQtyToDeliver(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return map.get(shipmentScheduleId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\QtyToDeliverMap.java | 1 |
请完成以下Java代码 | public final class KeyNamePair extends NamePair
{
public static final KeyNamePair of(
@Nullable final RepoIdAware key,
@Nullable final String name)
{
final int keyInt = key != null ? key.getRepoId() : EMPTY.getKey();
return of(keyInt, name, null/* description */);
}
public static final KeyNamePair of(
@Nullable final int key,
@Nullable final String name)
{
return of(key, name, null/* description */);
}
public static final KeyNamePair of(
@Nullable final RepoIdAware key,
@Nullable final String name,
@Nullable final String description)
{
final int keyInt = key != null ? key.getRepoId() : EMPTY.getKey();
return of(keyInt, name, description);
}
@JsonCreator
public static final KeyNamePair of(
@JsonProperty("k") final int key,
@JsonProperty("n") final String name,
@JsonProperty("description") final String description)
{
if (key == EMPTY.getKey() && Objects.equals(name, EMPTY.getName()))
{
return EMPTY;
}
return new KeyNamePair(key, name, description);
}
public static final KeyNamePair of(final int key)
{
if (key < 0)
{
return EMPTY;
}
return new KeyNamePair(key, "<" + key + ">", null/* help */);
}
private static final long serialVersionUID = 6347385376010388473L;
public static final KeyNamePair EMPTY = new KeyNamePair(-1, "", null/* description */);
/**
* @deprecated please use the static creator methods instead.
*/
@Deprecated
public KeyNamePair(final int key, final String name)
{
super(name, null/* description */);
this.m_key = key;
}
/**
* Constructor KeyValue Pair -
*
* @param key Key (-1 is considered as null)
* @param name string representation
* @deprecated please use the static creator methods instead.
*/
@Deprecated
public KeyNamePair(final int key, @Nullable final String name, @Nullable final String description)
{
super(name, description);
this.m_key = key;
}
/** The Key */ | private final int m_key;
/**
* Get Key
*
* @return key
*/
@JsonProperty("k")
public int getKey()
{
return m_key;
} // getKey
/**
* Get ID (key as String)
*
* @return String value of key or null if -1
*/
@Override
@JsonIgnore
public String getID()
{
if (m_key == -1)
return null;
return String.valueOf(m_key);
} // getID
/**
* Equals
*
* @param obj object
* @return true if equal
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof KeyNamePair)
{
KeyNamePair pp = (KeyNamePair)obj;
if (pp.getKey() == m_key
&& pp.getName() != null
&& pp.getName().equals(getName()))
return true;
return false;
}
return false;
} // equals
@Override
public int hashCode()
{
return Objects.hash(m_key);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\KeyNamePair.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class Album {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "album")
private List<Song> songs;
@ManyToMany(mappedBy = "followingAlbums")
private Set<User> followers;
Album(String name) {
this.name = name;
}
@Override | public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Album album = (Album) o;
return Objects.equals(id, album.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
protected Album() {
}
} | repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\multiplebagfetchexception\Album.java | 2 |
请完成以下Java代码 | public final class WebSocketUtils {
private static final Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);
// 存储 websocket session
public static final Map<String, Session> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>();
/**
* @param session 用户 session
* @param message 发送内容
*/
public static void sendMessage(Session session, String message) {
if (session == null) {
return;
}
final RemoteEndpoint.Basic basic = session.getBasicRemote(); | if (basic == null) {
return;
}
try {
basic.sendText(message);
} catch (IOException e) {
logger.error("sendMessage IOException ",e);
}
}
public static void sendMessageAll(String message) {
ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message));
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-10 课: 使用 Spring Boot WebSocket 创建聊天室\spring-boot-websocket\src\main\java\com\neo\utils\WebSocketUtils.java | 1 |
请完成以下Java代码 | public Integer getReadCount() {
return readCount;
}
public void setReadCount(Integer readCount) {
this.readCount = readCount;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(); | sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", categoryId=").append(categoryId);
sb.append(", icon=").append(icon);
sb.append(", title=").append(title);
sb.append(", showStatus=").append(showStatus);
sb.append(", createTime=").append(createTime);
sb.append(", readCount=").append(readCount);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelp.java | 1 |
请完成以下Java代码 | public long countByTenantId(TenantId tenantId) {
return deviceDao.countByTenantId(tenantId);
}
private final PaginatedRemover<TenantId, Device> tenantDevicesRemover = new PaginatedRemover<>() {
@Override
protected PageData<Device> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return deviceDao.findDevicesByTenantId(id.getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Device device) {
deleteDevice(tenantId, device);
}
};
private final PaginatedRemover<CustomerId, Device> customerDevicesRemover = new PaginatedRemover<>() {
@Override
protected PageData<Device> findEntities(TenantId tenantId, CustomerId id, PageLink pageLink) {
return deviceDao.findDevicesByTenantIdAndCustomerId(tenantId.getId(), id.getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Device entity) {
unassignDeviceFromCustomer(tenantId, new DeviceId(entity.getUuidId()));
}
}; | @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findDeviceById(tenantId, new DeviceId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findDeviceByIdAsync(tenantId, new DeviceId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\device\DeviceServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private NursingService getNursingServiceOrNull(
@NonNull final NursingServiceApi nursingServiceApi,
@NonNull final AlbertaConnectionDetails albertaConnectionDetails,
@Nullable final String nursingServiceId) throws ApiException
{
if (EmptyUtil.isBlank(nursingServiceId))
{
return null;
}
final NursingService nursingService = nursingServiceApi.getNursingService(albertaConnectionDetails.getApiKey(), nursingServiceId);
if (nursingService == null)
{
throw new RuntimeException("No info returned for nursingServiceId: " + nursingServiceId);
}
return nursingService;
}
@Nullable
private Hospital getHospital(
@NonNull final HospitalApi hospitalApi,
@NonNull final AlbertaConnectionDetails albertaConnectionDetails,
@Nullable final PatientHospital patientHospital) throws ApiException
{
if (patientHospital == null || EmptyUtil.isBlank(patientHospital.getHospitalId()))
{
return null;
}
final Hospital hospital = hospitalApi.getHospital(albertaConnectionDetails.getApiKey(), patientHospital.getHospitalId());
if (hospital == null)
{
throw new RuntimeException("No info returned for hospitalId: " + patientHospital.getHospitalId());
}
return hospital;
}
@Nullable
private Payer getPayerOrNull(
@NonNull final PayerApi payerApi,
@NonNull final AlbertaConnectionDetails albertaConnectionDetails,
@Nullable final PatientPayer patientPayer) throws ApiException
{
if (patientPayer == null || EmptyUtil.isBlank(patientPayer.getPayerId()))
{
return null;
}
final Payer payer = payerApi.getPayer(albertaConnectionDetails.getApiKey(), patientPayer.getPayerId());
if (payer == null)
{
throw new RuntimeException("No info returned for payer: " + patientPayer.getPayerId());
}
return payer;
}
@Nullable
private Pharmacy getPharmacyOrNull(
@NonNull final PharmacyApi pharmacyApi,
@NonNull final AlbertaConnectionDetails albertaConnectionDetails,
@Nullable final String pharmacyId) throws ApiException
{ | if (EmptyUtil.isBlank(pharmacyId))
{
return null;
}
final Pharmacy pharmacy = pharmacyApi.getPharmacy(albertaConnectionDetails.getApiKey(), pharmacyId);
if (pharmacy == null)
{
throw new RuntimeException("No info returned for pharmacy: " + pharmacyId);
}
return pharmacy;
}
@Nullable
private Users getUserOrNull(
@NonNull final UserApi userApi,
@NonNull final AlbertaConnectionDetails albertaConnectionDetails,
@Nullable final String userId) throws ApiException
{
if (EmptyUtil.isBlank(userId))
{
return null;
}
final Users user = userApi.getUser(albertaConnectionDetails.getApiKey(), userId);
if (user == null)
{
throw new RuntimeException("No info returned for user: " + userId);
}
return user;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\processor\CreateBPartnerReqProcessor.java | 2 |
请完成以下Java代码 | private static void errorfIfNotEqualsOperator(@NonNull final DocumentFilterParam parameter)
{
if (!Operator.EQUAL.equals(parameter.getOperator()))
{
final String message = StringUtils.formatMessage("The given DocumentFilterParam needs to have an EQUAL operator, but has {}", parameter.getOperator());
throw new AdempiereException(message).setParameter("DocumentFilterParam", parameter);
}
}
private static HuId extractHuId(@NonNull final DocumentFilterParam parameter)
{
return HuId.ofRepoIdOrNull(extractInt(parameter));
}
private static ImmutableSet<HuId> extractHuIds(@NonNull final DocumentFilterParam parameter)
{
final HuId huId = extractHuId(parameter);
return huId != null ? ImmutableSet.of(huId) : ImmutableSet.of();
}
private static int extractInt(@NonNull final DocumentFilterParam parameter)
{
final Object value = Check.assumeNotNull(parameter.getValue(), "Given paramter may not have a null value; parameter={}", parameter);
if (value instanceof LookupValue)
{
final LookupValue lookupValue = (LookupValue)value;
return lookupValue.getIdAsInt();
}
else if (value instanceof Integer)
{
return (Integer)value;
}
else
{
throw new AdempiereException("Unable to extract an integer ID from parameter=" + parameter);
}
}
private static String extractString(@NonNull final DocumentFilterParam parameter)
{
final Object value = Check.assumeNotNull(parameter.getValue(), "Given paramter may not have a null value; parameter={}", parameter);
if (value instanceof LookupValue)
{
final LookupValue lookupValue = (LookupValue)value; | return lookupValue.getIdAsString();
}
else if (value instanceof String)
{
return (String)value;
}
throw Check.fail("Unable to extract a String from parameter={}", parameter);
}
private static Boolean extractBoolean(@NonNull final DocumentFilterParam parameter)
{
final Object value = Check.assumeNotNull(parameter.getValue(), "Given parameter may not have a null value; parameter={}", parameter);
if (value instanceof Boolean)
{
return (Boolean)value;
}
throw Check.fail("Unable to extract a Boolean from parameter={}", parameter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\trace\HuTraceQueryCreator.java | 1 |
请完成以下Java代码 | private String getAction(NoSuchMethodDescriptor callerDescriptor, NoSuchMethodDescriptor calledDescriptor) {
if (callerDescriptor.getClassName().equals(calledDescriptor.getClassName())) {
return "Correct the classpath of your application so that it contains a single, compatible version of "
+ calledDescriptor.getClassName();
}
else {
return "Correct the classpath of your application so that it contains compatible versions of the classes "
+ callerDescriptor.getClassName() + " and " + calledDescriptor.getClassName();
}
}
protected static class NoSuchMethodDescriptor {
private final String errorMessage;
private final String className;
private final List<URL> candidateLocations;
private final List<ClassDescriptor> typeHierarchy;
public NoSuchMethodDescriptor(String errorMessage, String className, List<URL> candidateLocations,
List<ClassDescriptor> typeHierarchy) {
this.errorMessage = errorMessage;
this.className = className;
this.candidateLocations = candidateLocations;
this.typeHierarchy = typeHierarchy;
}
public String getErrorMessage() {
return this.errorMessage;
}
public String getClassName() {
return this.className;
}
public List<URL> getCandidateLocations() {
return this.candidateLocations;
}
public List<ClassDescriptor> getTypeHierarchy() {
return this.typeHierarchy;
} | }
protected static class ClassDescriptor {
private final String name;
private final URL location;
public ClassDescriptor(String name, URL location) {
this.name = name;
this.location = location;
}
public String getName() {
return this.name;
}
public URL getLocation() {
return this.location;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\NoSuchMethodFailureAnalyzer.java | 1 |
请完成以下Java代码 | public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getSourceState() {
return sourceState;
}
public void setSourceState(String sourceState) {
this.sourceState = sourceState;
}
public String getTargetState() {
return targetState;
}
public void setTargetState(String targetState) {
this.targetState = targetState;
}
public String getImplementationType() {
return implementationType;
}
public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public String getOnTransaction() {
return onTransaction;
}
public void setOnTransaction(String onTransaction) {
this.onTransaction = onTransaction;
}
/**
* Return the script info, if present.
* <p>
* ScriptInfo must be populated, when {@code <executionListener type="script" ...>} e.g. when
* implementationType is 'script'.
* </p> | */
public ScriptInfo getScriptInfo() {
return scriptInfo;
}
/**
* Sets the script info
*
* @see #getScriptInfo()
*/
public void setScriptInfo(ScriptInfo scriptInfo) {
this.scriptInfo = scriptInfo;
}
public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance;
}
@Override
public FlowableListener clone() {
FlowableListener clone = new FlowableListener();
clone.setValues(this);
return clone;
}
public void setValues(FlowableListener otherListener) {
super.setValues(otherListener);
setEvent(otherListener.getEvent());
setSourceState(otherListener.getSourceState());
setTargetState(otherListener.getTargetState());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
setOnTransaction(otherListener.getOnTransaction());
Optional.ofNullable(otherListener.getScriptInfo()).map(ScriptInfo::clone).ifPresent(this::setScriptInfo);
fieldExtensions = new ArrayList<>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\FlowableListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public JwtTokenFilter jwtTokenFilter() {
return new JwtTokenFilter();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.cors()
.and()
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS)
.permitAll()
.antMatchers("/graphiql")
.permitAll()
.antMatchers("/graphql")
.permitAll()
.antMatchers(HttpMethod.GET, "/articles/feed")
.authenticated()
.antMatchers(HttpMethod.POST, "/users", "/users/login")
.permitAll()
.antMatchers(HttpMethod.GET, "/articles/**", "/profiles/**", "/tags")
.permitAll()
.anyRequest()
.authenticated(); | http.addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(asList("*"));
configuration.setAllowedMethods(asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must not be the
// wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(false);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(asList("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\security\WebSecurityConfig.java | 2 |
请完成以下Java代码 | public String getMessageID ()
{
return (String)get_Value(COLUMNNAME_MessageID);
}
public I_R_MailText getR_MailText() throws RuntimeException
{
return (I_R_MailText)MTable.get(getCtx(), I_R_MailText.Table_Name)
.getPO(getR_MailText_ID(), get_TrxName()); }
/** Set Mail Template.
@param R_MailText_ID
Text templates for mailings
*/
public void setR_MailText_ID (int R_MailText_ID)
{
if (R_MailText_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_MailText_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_MailText_ID, Integer.valueOf(R_MailText_ID));
}
/** Get Mail Template.
@return Text templates for mailings
*/
public int getR_MailText_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_MailText_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Subject.
@param Subject
Email Message Subject
*/
public void setSubject (String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Subject.
@return Email Message Subject
*/
public String getSubject ()
{ | return (String)get_Value(COLUMNNAME_Subject);
}
public I_W_MailMsg getW_MailMsg() throws RuntimeException
{
return (I_W_MailMsg)MTable.get(getCtx(), I_W_MailMsg.Table_Name)
.getPO(getW_MailMsg_ID(), get_TrxName()); }
/** Set Mail Message.
@param W_MailMsg_ID
Web Store Mail Message Template
*/
public void setW_MailMsg_ID (int W_MailMsg_ID)
{
if (W_MailMsg_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, Integer.valueOf(W_MailMsg_ID));
}
/** Get Mail Message.
@return Web Store Mail Message Template
*/
public int getW_MailMsg_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_MailMsg_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserMail.java | 1 |
请完成以下Java代码 | public Void execute(CommandContext commandContext) {
if (taskId != null) {
deleteTask(taskId, commandContext);
} else if (taskIds != null) {
for (String taskId : taskIds) {
deleteTask(taskId, commandContext);
}
} else {
throw new ProcessEngineException("taskId and taskIds are null");
}
return null;
}
protected void deleteTask(String taskId, CommandContext commandContext) {
TaskManager taskManager = commandContext.getTaskManager();
TaskEntity task = taskManager.findTaskById(taskId);
if (task != null) {
if(task.getExecutionId() != null) {
throw new ProcessEngineException("The task cannot be deleted because is part of a running process");
} else if (task.getCaseExecutionId() != null) {
throw new ProcessEngineException("The task cannot be deleted because is part of a running case instance"); | }
checkDeleteTask(task, commandContext);
task.logUserOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE);
String reason = (deleteReason == null || deleteReason.length() == 0) ? TaskEntity.DELETE_REASON_DELETED : deleteReason;
task.delete(reason, cascade);
} else if (cascade) {
Context
.getCommandContext()
.getHistoricTaskInstanceManager()
.deleteHistoricTaskInstanceById(taskId);
}
}
protected void checkDeleteTask(TaskEntity task, CommandContext commandContext) {
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkDeleteTask(task);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteTaskCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommentsService {
@Autowired
private OAuth2RestOperations restTemplate;
/**
* Returns the comments for the task; note that this applies a circuit
* breaker that would return the default value if the comments-webservice
* was down.
*
* Discussion on HystrixProperty
* <ol>
* <li><b>execution.isolation.strategy:</b> The value of "SEMAPHORE" enables
* Hystrix to use the current thread for executing this command. Since we
* need to use the parent HttpRequest to pass the OAuth2 access token, we
* are constrained in using the calling thread. The number of concurrent
* requests that can be made to the command is limited by the semaphore(or
* counter) value; default is 10.In a normal scenario, you would use
* isolation strategy of "THREAD" that executes the Hystrix command in a
* separate thread pool. This is desirable because it doesn't block the
* calling thread and lets us handle faulty client libraries, client
* performance considerations etc.</li>
* <li><b>circuitBreaker.requestVolumeThreshold:</b>This property sets the
* minimum number of requests in a rolling window that will trip the
* circuit. For example, if the value is 20, then if only 19 requests are
* received in the rolling window (say a window of 10 seconds) the circuit
* will not trip open even if all 19 failed. We have a lower value in this
* sample application so as to trip early.</li>
* <li><b>circuitBreaker.sleepWindowInMilliseconds:</b>This property sets
* the amount of time, after tripping the circuit, to reject requests before
* allowing attempts again to determine if the circuit should again be
* closed. We again have a lower value so that Hystrix tries to pass single
* request to the called service quickly.</li>
* </ol>
*
* @param taskId
* @return
*/
@HystrixCommand(fallbackMethod = "getFallbackCommentsForTask", commandProperties = {
@HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"), | @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1000") })
public CommentCollectionResource getCommentsForTask(String taskId) {
// Get the comments for this task
return restTemplate.getForObject(String.format("http://comments-webservice/comments/%s", taskId),
CommentCollectionResource.class);
}
/**
* Gets the default comments for task. Need to add the suppress warning
* since the method is not directly used by the class.
*
* @return the default comments for task
*/
@SuppressWarnings("unused")
private CommentCollectionResource getFallbackCommentsForTask(String taskId) {
// Get the default comments
CommentCollectionResource comments = new CommentCollectionResource();
comments.addComment(new CommentResource(taskId, "default comment", Calendar.getInstance().getTime()));
return comments;
}
} | repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\apis\CommentsService.java | 2 |
请完成以下Java代码 | public CardPaymentServiceType2Code getAddtlSvc() {
return addtlSvc;
}
/**
* Sets the value of the addtlSvc property.
*
* @param value
* allowed object is
* {@link CardPaymentServiceType2Code }
*
*/
public void setAddtlSvc(CardPaymentServiceType2Code value) {
this.addtlSvc = value;
}
/**
* Gets the value of the txCtgy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTxCtgy() {
return txCtgy;
}
/**
* Sets the value of the txCtgy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTxCtgy(String value) {
this.txCtgy = value;
}
/**
* Gets the value of the saleRcncltnId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSaleRcncltnId() {
return saleRcncltnId;
}
/**
* Sets the value of the saleRcncltnId property.
*
* @param value
* allowed object is | * {@link String }
*
*/
public void setSaleRcncltnId(String value) {
this.saleRcncltnId = value;
}
/**
* Gets the value of the seqNbRg property.
*
* @return
* possible object is
* {@link CardSequenceNumberRange1 }
*
*/
public CardSequenceNumberRange1 getSeqNbRg() {
return seqNbRg;
}
/**
* Sets the value of the seqNbRg property.
*
* @param value
* allowed object is
* {@link CardSequenceNumberRange1 }
*
*/
public void setSeqNbRg(CardSequenceNumberRange1 value) {
this.seqNbRg = value;
}
/**
* Gets the value of the txDtRg property.
*
* @return
* possible object is
* {@link DateOrDateTimePeriodChoice }
*
*/
public DateOrDateTimePeriodChoice getTxDtRg() {
return txDtRg;
}
/**
* Sets the value of the txDtRg property.
*
* @param value
* allowed object is
* {@link DateOrDateTimePeriodChoice }
*
*/
public void setTxDtRg(DateOrDateTimePeriodChoice value) {
this.txDtRg = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardAggregated1.java | 1 |
请完成以下Java代码 | public class ContractBillLocationAdapter implements IDocumentBillLocationAdapter, RecordBasedLocationAdapter<ContractBillLocationAdapter>
{
private final I_C_Flatrate_Term delegate;
@Getter
@Setter
private String billToAddress;
public ContractBillLocationAdapter(@NonNull final I_C_Flatrate_Term delegate)
{
this.delegate = delegate;
}
@Override
public int getBill_BPartner_ID()
{
return delegate.getBill_BPartner_ID();
}
@Override
public void setBill_BPartner_ID(final int Bill_BPartner_ID)
{
delegate.setBill_BPartner_ID(Bill_BPartner_ID);
}
@Override
public int getBill_Location_ID()
{
return delegate.getBill_Location_ID();
}
@Override
public void setBill_Location_ID(final int Bill_Location_ID)
{
delegate.setBill_Location_ID(Bill_Location_ID);
}
@Override
public int getBill_Location_Value_ID()
{
return delegate.getBill_Location_Value_ID();
}
@Override
public void setBill_Location_Value_ID(final int Bill_Location_Value_ID)
{
delegate.setBill_Location_Value_ID(Bill_Location_Value_ID);
}
@Override
public int getBill_User_ID()
{
return delegate.getBill_User_ID();
} | @Override
public void setBill_User_ID(final int Bill_User_ID)
{
delegate.setBill_User_ID(Bill_User_ID);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddress(from);
}
@Override
public I_C_Flatrate_Term getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public ContractBillLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new ContractBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Flatrate_Term.class));
}
public void setFrom(final @NonNull BPartnerLocationAndCaptureId billToLocationId, final @Nullable BPartnerContactId billToContactId)
{
setBill_BPartner_ID(billToLocationId.getBpartnerRepoId());
setBill_Location_ID(billToLocationId.getBPartnerLocationRepoId());
setBill_Location_Value_ID(billToLocationId.getLocationCaptureRepoId());
setBill_User_ID(billToContactId == null ? -1 : billToContactId.getRepoId());
}
public void setFrom(final @NonNull BPartnerLocationAndCaptureId billToLocationId)
{
setBill_BPartner_ID(billToLocationId.getBpartnerRepoId());
setBill_Location_ID(billToLocationId.getBPartnerLocationRepoId());
setBill_Location_Value_ID(billToLocationId.getLocationCaptureRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\location\adapter\ContractBillLocationAdapter.java | 1 |
请完成以下Java代码 | private void stopIfNoSubscription()
{
if (hasActiveSubscriptions())
{
return;
}
final boolean wasRunning = running.getAndSet(false);
if (wasRunning)
{
producerControls.onStop();
}
stopScheduledFuture();
logger.debug("{} stopped", this);
}
private void startScheduledFutureIfApplies()
{
// Does not apply
if (onPollingEventsSupplier == null)
{
return;
}
//
// Check if the producer was already scheduled
if (scheduledFuture != null)
{
return;
}
//
// Schedule producer
final long initialDelayMillis = 1000;
final long periodMillis = 1000;
scheduledFuture = scheduler.scheduleAtFixedRate(this::pollAndPublish, initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS);
logger.trace("{}: start producing using initialDelayMillis={}, periodMillis={}", this, initialDelayMillis, periodMillis);
}
private void stopScheduledFuture()
{
if (scheduledFuture == null)
{
return;
}
try
{
scheduledFuture.cancel(true);
}
catch (final Exception ex)
{
logger.warn("{}: Failed stopping scheduled future: {}. Ignored and considering it as stopped", this, scheduledFuture, ex);
}
scheduledFuture = null;
}
private void pollAndPublish()
{ | if (onPollingEventsSupplier == null)
{
return;
}
try
{
final List<?> events = onPollingEventsSupplier.produceEvents();
if (events != null && !events.isEmpty())
{
for (final Object event : events)
{
websocketSender.convertAndSend(topicName, event);
logger.trace("Event sent to {}: {}", topicName, event);
}
}
else
{
logger.trace("Got no events from {}", onPollingEventsSupplier);
}
}
catch (final Exception ex)
{
logger.warn("Failed producing event for {}. Ignored.", this, ex);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducersRegistry.java | 1 |
请完成以下Java代码 | public String toString() {return name;}
public String getAsString() {return name;}
@Override
public int compareTo(@NonNull final AccountConceptualName other)
{
return this.name.compareTo(other.name);
}
public static boolean equals(@Nullable final AccountConceptualName o1, @Nullable final AccountConceptualName o2) {return Objects.equals(o1, o2);}
public boolean isAnyOf(@Nullable final AccountConceptualName... names)
{
if (names == null)
{
return false;
}
for (final AccountConceptualName name : names)
{
if (name != null && equals(this, name))
{
return true; | }
}
return false;
}
public boolean isProductMandatory()
{
return isAnyOf(P_Asset_Acct);
}
public boolean isWarehouseLocatorMandatory()
{
return isAnyOf(P_Asset_Acct);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\AccountConceptualName.java | 1 |
请完成以下Java代码 | public final ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
final String tableName = context.getTableName();
if (!Objects.equals(tableName, I_C_Flatrate_Term.Table_Name) && !Objects.equals(tableName, I_C_SubscriptionProgress.Table_Name))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Only for C_Flatrate_Term and C_SubscriptionProgress; not for tableName=" + tableName);
}
final I_C_Flatrate_Term term = getTermFromPreconditionsContext(context);
if (term == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Only if a term is actually selected");
}
if (!Objects.equals(X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription, term.getType_Conditions()))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Only for Type_Conditions=Subscr; not for " + term.getType_Conditions());
}
if (!term.isActive())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Only for active terms");
}
if (!Objects.equals(term.getDocStatus(), IDocument.STATUS_Completed))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Only for DocStatus='CO' terms; not for " + term.getDocStatus());
}
return ProcessPreconditionsResolution.accept();
}
private final I_C_Flatrate_Term getTermFromPreconditionsContext(@NonNull final IProcessPreconditionsContext context)
{
final String tableName = context.getTableName(); | if (Objects.equals(tableName, I_C_Flatrate_Term.Table_Name))
{
return context.getSelectedModel(I_C_Flatrate_Term.class);
}
else if (Objects.equals(tableName, I_C_SubscriptionProgress.Table_Name))
{
return context.getSelectedModel(I_C_SubscriptionProgress.class).getC_Flatrate_Term();
}
final String message = StringUtils.formatMessage("Process is called with TableName={}; preconditionsContext={}; this={}", tableName, context, this);
throw new IllegalStateException(message);
}
protected final I_C_Flatrate_Term getTermFromProcessInfo()
{
if (Objects.equals(getTableName(), I_C_Flatrate_Term.Table_Name))
{
return getRecord(I_C_Flatrate_Term.class);
}
else if (Objects.equals(getTableName(), I_C_SubscriptionProgress.Table_Name))
{
return getRecord(I_C_SubscriptionProgress.class).getC_Flatrate_Term();
}
final String message = StringUtils.formatMessage("Process is called with TableName={}; processInfo={}; this={}", getTableName(), getProcessInfo(), this);
throw new IllegalStateException(message);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\process\C_SubscriptionProgressBase.java | 1 |
请完成以下Java代码 | public DataObjectReference newInstance(ModelTypeInstanceContext instanceContext) {
return new DataObjectReferenceImpl(instanceContext);
}
});
itemSubjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ITEM_SUBJECT_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
dataObjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_DATA_OBJECT_REF)
.idAttributeReference(DataObject.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataStateChild = sequenceBuilder.element(DataState.class)
.build();
typeBuilder.build();
}
public DataObjectReferenceImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public ItemDefinition getItemSubject() {
return itemSubjectRefAttribute.getReferenceTargetElement(this);
}
public void setItemSubject(ItemDefinition itemSubject) { | itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject);
}
public DataState getDataState() {
return dataStateChild.getChild(this);
}
public void setDataState(DataState dataState) {
dataStateChild.setChild(this, dataState);
}
public DataObject getDataObject() {
return dataObjectRefAttribute.getReferenceTargetElement(this);
}
public void setDataObject(DataObject dataObject) {
dataObjectRefAttribute.setReferenceTargetElement(this, dataObject);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataObjectReferenceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Author fetchAuthor(long id) {
return authorRepository.findById(id).orElseThrow();
}
// second query/request
@Transactional(readOnly = true)
public List<Book> fetchBooksOfAuthorBad(Author a) {
Author author = fetchAuthor(a.getId());
List<Book> books = author.getBooks();
Hibernate.initialize(books);
// books.size();
return books;
}
// second query/request
public List<Book> fetchBooksOfAuthorGood(Author a) {
// Explicit JPQL
// return bookRepository.fetchByAuthor(a);
// Query Builder
return bookRepository.findByAuthor(a);
}
// first query/request
public Book fetchBook(long id) {
return bookRepository.findById(id).orElseThrow();
}
// second query/request
@Transactional(readOnly = true)
public Author fetchAuthorOfBookBad(Book b) { | Book book = fetchBook(b.getId());
Author author = book.getAuthor();
Hibernate.initialize(author);
return author;
}
// second query/request
public Author fetchAuthorOfBookGood(Book b) {
// Explicit JPQL
// return authorRepository.fetchByBooks(b);
// Query Builder
return authorRepository.findByBooks(b);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootParentChildSeparateQueries\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public java.lang.String getScheduleType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ScheduleType);
}
/**
* Status AD_Reference_ID=540218
* Reference name: AD_Scheduler Status
*/
public static final int STATUS_AD_Reference_ID=540218;
/** New = NEW */
public static final String STATUS_New = "NEW";
/** Started = STARTED */
public static final String STATUS_Started = "STARTED";
/** Running = RUNNING */
public static final String STATUS_Running = "RUNNING";
/** Stopped = STOPPED */
public static final String STATUS_Stopped = "STOPPED";
/** Set Status.
@param Status
Status of the currently running check
*/
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
@Override
public org.compiere.model.I_AD_User getSupervisor() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSupervisor(org.compiere.model.I_AD_User Supervisor)
{
set_ValueFromPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class, Supervisor);
}
/** Set Vorgesetzter.
@param Supervisor_ID
Supervisor for this user/organization - used for escalation and approval
*/
@Override
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Vorgesetzter.
@return Supervisor for this user/organization - used for escalation and approval
*/
@Override
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** | * WeekDay AD_Reference_ID=167
* Reference name: Weekdays
*/
public static final int WEEKDAY_AD_Reference_ID=167;
/** Sonntag = 7 */
public static final String WEEKDAY_Sonntag = "7";
/** Montag = 1 */
public static final String WEEKDAY_Montag = "1";
/** Dienstag = 2 */
public static final String WEEKDAY_Dienstag = "2";
/** Mittwoch = 3 */
public static final String WEEKDAY_Mittwoch = "3";
/** Donnerstag = 4 */
public static final String WEEKDAY_Donnerstag = "4";
/** Freitag = 5 */
public static final String WEEKDAY_Freitag = "5";
/** Samstag = 6 */
public static final String WEEKDAY_Samstag = "6";
/** Set Day of the Week.
@param WeekDay
Day of the Week
*/
@Override
public void setWeekDay (java.lang.String WeekDay)
{
set_Value (COLUMNNAME_WeekDay, WeekDay);
}
/** Get Day of the Week.
@return Day of the Week
*/
@Override
public java.lang.String getWeekDay ()
{
return (java.lang.String)get_Value(COLUMNNAME_WeekDay);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Scheduler.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_BP_Group getImportedMunicipalityBP_Group()
{
return get_ValueAsPO(COLUMNNAME_ImportedMunicipalityBP_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setImportedMunicipalityBP_Group(final org.compiere.model.I_C_BP_Group ImportedMunicipalityBP_Group)
{
set_ValueFromPO(COLUMNNAME_ImportedMunicipalityBP_Group_ID, org.compiere.model.I_C_BP_Group.class, ImportedMunicipalityBP_Group);
}
@Override
public void setImportedMunicipalityBP_Group_ID (final int ImportedMunicipalityBP_Group_ID)
{
if (ImportedMunicipalityBP_Group_ID < 1)
set_Value (COLUMNNAME_ImportedMunicipalityBP_Group_ID, null);
else
set_Value (COLUMNNAME_ImportedMunicipalityBP_Group_ID, ImportedMunicipalityBP_Group_ID);
}
@Override
public int getImportedMunicipalityBP_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_ImportedMunicipalityBP_Group_ID);
}
@Override
public org.compiere.model.I_C_BP_Group getImportedPartientBP_Group()
{
return get_ValueAsPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setImportedPartientBP_Group(final org.compiere.model.I_C_BP_Group ImportedPartientBP_Group)
{
set_ValueFromPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class, ImportedPartientBP_Group);
}
@Override
public void setImportedPartientBP_Group_ID (final int ImportedPartientBP_Group_ID)
{
if (ImportedPartientBP_Group_ID < 1)
set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, null);
else
set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, ImportedPartientBP_Group_ID);
} | @Override
public int getImportedPartientBP_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_ImportedPartientBP_Group_ID);
}
@Override
public void setStoreDirectory (final @Nullable java.lang.String StoreDirectory)
{
set_Value (COLUMNNAME_StoreDirectory, StoreDirectory);
}
@Override
public java.lang.String getStoreDirectory()
{
return get_ValueAsString(COLUMNNAME_StoreDirectory);
}
@Override
public void setVia_EAN (final java.lang.String Via_EAN)
{
set_Value (COLUMNNAME_Via_EAN, Via_EAN);
}
@Override
public java.lang.String getVia_EAN()
{
return get_ValueAsString(COLUMNNAME_Via_EAN);
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java-gen\de\metas\vertical\healthcare\forum_datenaustausch_ch\commons\model\X_HC_Forum_Datenaustausch_Config.java | 1 |
请完成以下Java代码 | public I_M_Attribute retrieveAttribute(final AttributeSetId attributeSetId, final AttributeId attributeId)
{
if (!containsAttribute(attributeSetId, attributeId))
{
return null;
}
return getAttributeRecordById(attributeId);
}
private static final class AttributeListValueMap
{
public static AttributeListValueMap ofList(final List<AttributeListValue> list)
{
if (list.isEmpty())
{
return EMPTY;
}
return new AttributeListValueMap(list);
}
private static final AttributeListValueMap EMPTY = new AttributeListValueMap();
private final ImmutableMap<String, AttributeListValue> map;
private AttributeListValueMap()
{ | map = ImmutableMap.of();
}
private AttributeListValueMap(@NonNull final List<AttributeListValue> list)
{
map = Maps.uniqueIndex(list, AttributeListValue::getValue);
}
public List<AttributeListValue> toList()
{
return ImmutableList.copyOf(map.values());
}
@Nullable
public AttributeListValue getByIdOrNull(@NonNull final AttributeValueId id)
{
return map.values()
.stream()
.filter(av -> AttributeValueId.equals(av.getId(), id))
.findFirst()
.orElse(null);
}
public AttributeListValue getByValueOrNull(final String value)
{
return map.get(value);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeDAO.java | 1 |
请完成以下Java代码 | public class JSONUserSessionChangesEvent
{
/** user's full name/display name */
@JsonProperty("fullname")
@JsonInclude(JsonInclude.Include.NON_NULL)
private final String fullname;
@JsonProperty("email")
@JsonInclude(JsonInclude.Include.NON_NULL)
private final String email;
@JsonProperty("avatarId")
@JsonInclude(JsonInclude.Include.NON_NULL)
// IMPORTANT: empty avatarId is perfectly valid and means the avatar was removed
private final String avatarId;
@JsonProperty("language")
@JsonInclude(JsonInclude.Include.NON_NULL)
private final JSONLookupValue language;
@JsonProperty("timestamp") | private final String timestamp = DateTimeConverters.toJson(SystemTime.asInstant(), de.metas.common.util.time.SystemTime.zoneId());
@JsonProperty("defaultBoilerPlateId")
@JsonInclude(JsonInclude.Include.NON_NULL)
private final BoilerPlateId defaultBoilerPlateId;
@JsonProperty("defaultFlatrateConditionsId")
@JsonInclude(JsonInclude.Include.NON_NULL)
private final ConditionsId defaultFlatrateConditionsId;
public boolean isEmpty()
{
return fullname == null
&& email == null
&& avatarId == null
&& language == null
&& defaultBoilerPlateId == null
&& defaultFlatrateConditionsId == null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\json\JSONUserSessionChangesEvent.java | 1 |
请完成以下Java代码 | public List<Event> findEventsByTaskId(String taskId) {
checkHistoryEnabled();
return getDbSqlSession().selectList("selectEventsByTaskId", taskId);
}
@SuppressWarnings("unchecked")
public List<Event> findEventsByProcessInstanceId(String processInstanceId) {
checkHistoryEnabled();
return getDbSqlSession().selectList("selectEventsByProcessInstanceId", processInstanceId);
}
public void deleteCommentsByTaskId(String taskId) {
checkHistoryEnabled();
getDbSqlSession().delete("deleteCommentsByTaskId", taskId);
}
public void deleteCommentsByProcessInstanceId(String processInstanceId) {
checkHistoryEnabled();
getDbSqlSession().delete("deleteCommentsByProcessInstanceId", processInstanceId);
}
@SuppressWarnings("unchecked")
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) {
checkHistoryEnabled();
return getDbSqlSession().selectList("selectCommentsByProcessInstanceId", processInstanceId);
} | public List<Comment> findCommentsByProcessInstanceId(String processInstanceId, String type) {
checkHistoryEnabled();
Map<String, Object> params = new HashMap<>();
params.put("processInstanceId", processInstanceId);
params.put("type", type);
return getDbSqlSession().selectListWithRawParameter("selectCommentsByProcessInstanceIdAndType", params, 0, Integer.MAX_VALUE);
}
public Comment findComment(String commentId) {
return getDbSqlSession().selectById(CommentEntity.class, commentId);
}
public Event findEvent(String commentId) {
return getDbSqlSession().selectById(CommentEntity.class, commentId);
}
protected void checkHistoryEnabled() {
if (!getHistoryManager().isHistoryEnabled()) {
throw new ActivitiException("In order to use comments, history should be enabled");
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRepairsResolution() {
return repairsResolution;
}
public void setRepairsResolution(String repairsResolution) {
this.repairsResolution = repairsResolution;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceAppraisalLine deviceAppraisalLine = (DeviceAppraisalLine) o;
return Objects.equals(this.description, deviceAppraisalLine.description) &&
Objects.equals(this.additionalDescription, deviceAppraisalLine.additionalDescription) &&
Objects.equals(this.repairsReason, deviceAppraisalLine.repairsReason) &&
Objects.equals(this.repairsResolution, deviceAppraisalLine.repairsResolution);
}
@Override
public int hashCode() {
return Objects.hash(description, additionalDescription, repairsReason, repairsResolution);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceAppraisalLine {\n"); | sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" additionalDescription: ").append(toIndentedString(additionalDescription)).append("\n");
sb.append(" repairsReason: ").append(toIndentedString(repairsReason)).append("\n");
sb.append(" repairsResolution: ").append(toIndentedString(repairsResolution)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceAppraisalLine.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.