instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
} | public StoreItem(String type, String name, Long price) {
this.type = type;
this.name = name;
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StoreItem storeItem = (StoreItem) o;
return Objects.equals(type, storeItem.type) && Objects.equals(name, storeItem.name) && Objects.equals(price, storeItem.price);
}
@Override
public int hashCode() {
return Objects.hash(type, name, price);
}
} | repos\tutorials-master\persistence-modules\spring-data-elasticsearch\src\main\java\com\baeldung\spring\data\es\aggregation\model\StoreItem.java | 1 |
请完成以下Java代码 | public int getRevision() {
return revision;
}
@Override
public int getRevisionNext() {
return revision + 1;
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override | public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public boolean hasEditorSource() {
return this.editorSourceValueId != null;
}
@Override
public boolean hasEditorSourceExtra() {
return this.editorSourceExtraValueId != null;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntity.java | 1 |
请完成以下Java代码 | public void setDataEntry_SubTab(final de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab)
{
set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab);
}
@Override
public void setDataEntry_SubTab_ID (final int DataEntry_SubTab_ID)
{
if (DataEntry_SubTab_ID < 1)
set_Value (COLUMNNAME_DataEntry_SubTab_ID, null);
else
set_Value (COLUMNNAME_DataEntry_SubTab_ID, DataEntry_SubTab_ID);
}
@Override
public int getDataEntry_SubTab_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_SubTab_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);
}
@Override
public void setIsInitiallyClosed (final boolean IsInitiallyClosed)
{
set_Value (COLUMNNAME_IsInitiallyClosed, IsInitiallyClosed);
}
@Override
public boolean isInitiallyClosed()
{
return get_ValueAsBoolean(COLUMNNAME_IsInitiallyClosed);
}
@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 setSectionName (final java.lang.String SectionName)
{
set_Value (COLUMNNAME_SectionName, SectionName);
}
@Override
public java.lang.String getSectionName()
{
return get_ValueAsString(COLUMNNAME_SectionName);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Section.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isEnableLocalization() {
return enableLocalization;
}
public TaskServiceConfiguration setEnableLocalization(boolean enableLocalization) {
this.enableLocalization = enableLocalization;
return this;
}
public TaskQueryInterceptor getTaskQueryInterceptor() {
return taskQueryInterceptor;
}
public TaskServiceConfiguration setTaskQueryInterceptor(TaskQueryInterceptor taskQueryInterceptor) {
this.taskQueryInterceptor = taskQueryInterceptor;
return this;
}
public HistoricTaskQueryInterceptor getHistoricTaskQueryInterceptor() {
return historicTaskQueryInterceptor;
}
public TaskServiceConfiguration setHistoricTaskQueryInterceptor(HistoricTaskQueryInterceptor historicTaskQueryInterceptor) {
this.historicTaskQueryInterceptor = historicTaskQueryInterceptor;
return this;
}
public boolean isEnableHistoricTaskLogging() {
return enableHistoricTaskLogging;
}
public TaskServiceConfiguration setEnableHistoricTaskLogging(boolean enableHistoricTaskLogging) {
this.enableHistoricTaskLogging = enableHistoricTaskLogging;
return this;
}
@Override
public TaskServiceConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) {
this.enableEventDispatcher = enableEventDispatcher;
return this;
} | @Override
public TaskServiceConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
return this;
}
@Override
public TaskServiceConfiguration setEventListeners(List<FlowableEventListener> eventListeners) {
this.eventListeners = eventListeners;
return this;
}
@Override
public TaskServiceConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) {
this.typedEventListeners = typedEventListeners;
return this;
}
public TaskPostProcessor getTaskPostProcessor() {
return taskPostProcessor;
}
public TaskServiceConfiguration setTaskPostProcessor(TaskPostProcessor processor) {
this.taskPostProcessor = processor;
return this;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\TaskServiceConfiguration.java | 2 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
sp | ring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
logging.level.org.hibernate.type.descriptor.sql=TRACE | repos\Hibernate-SpringBoot-master\HibernateSpringBootCustomSequenceGenerator\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessDefinitionUrl() {
return processDefinitionUrl;
}
public void setProcessDefinitionUrl(String processDefinitionUrl) {
this.processDefinitionUrl = processDefinitionUrl;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getExecutionUrl() {
return executionUrl;
}
public void setExecutionUrl(String executionUrl) {
this.executionUrl = executionUrl;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getScopeType() {
return scopeType;
} | public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\EventSubscriptionResponse.java | 2 |
请完成以下Java代码 | public List<DeadLetterJobEntity> findDeadLetterJobsByExecutionId(String executionId) {
return getDbSqlSession().selectList("selectDeadLetterJobsByExecutionId", executionId);
}
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) {
final String query = "selectDeadLetterJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionKeyNoTenantId(String jobHandlerType, String processDefinitionKey) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionKeyNoTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionKeyAndTenantId(String jobHandlerType, String processDefinitionKey, String tenantId) {
Map<String, String> params = new HashMap<>(3);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
params.put("tenantId", tenantId);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionKeyAndTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionId(String jobHandlerType, String processDefinitionId) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionId", processDefinitionId); | return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionId", params);
}
public long findDeadLetterJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectDeadLetterJobCountByQueryCriteria", jobQuery);
}
public void updateDeadLetterJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateDeadLetterJobTenantIdForDeployment", params);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeadLetterJobEntityManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static String getStringByStringMap(Map<String, String> map) {
SortedMap<String, Object> smap = new TreeMap<String, Object>(map);
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Object> m : smap.entrySet()) {
sb.append(m.getKey()).append("=").append(m.getValue()).append("&");
}
sb.delete(sb.length() - 1, sb.length());
return sb.toString();
}
/**
* 解析微信发来的请求(XML)
*
* @param inputStream
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(InputStream inputStream) throws Exception {
if (inputStream == null) {
return null;
}
Map<String, String> map = new HashMap<String, String>();// 将解析结果存储在HashMap中
SAXReader reader = new SAXReader();// 读取输入流
Document document = reader.read(inputStream);
Element root = document.getRootElement();// 得到xml根元素
List<Element> elementList = root.elements();// 得到根元素的所有子节点
for (Element e : elementList) { // 遍历所有子节点
map.put(e.getName(), e.getText());
}
inputStream.close(); // 释放资源
inputStream = null;
return map;
} | /**
* 订单查询
*
* @param outTradeNo
* @return
*/
public static Map<String, Object> orderQuery(String outTradeNo, String appId, String MchId, String partnerKey) {
Random random = new Random();
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("appid", appId);
paramMap.put("mch_id", MchId);
String nonce_str = "";
for (int i = 0; i < 31; i++) {
nonce_str += random.nextInt(10);
}
paramMap.put("nonce_str", nonce_str);
paramMap.put("out_trade_no", outTradeNo);
String signStr = getStringByMap(paramMap) + "&key=" + partnerKey;
paramMap.put("sign", MD5Util.encode(signStr).toUpperCase());
Set<String> ks = paramMap.keySet();
StringBuilder sb = new StringBuilder("<xml>");
for (String key : ks) {
sb.append("<" + key + ">" + paramMap.get(key) + "</" + key + ">");
}
sb.append("</xml>");
Map<String, Object> resultMap = httpXmlRequest("https://api.mch.weixin.qq.com/pay/orderquery", "POST",
sb.toString());
return resultMap;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\WeiXinPayUtils.java | 2 |
请完成以下Java代码 | public Optional<DeviceAccessor> getDeviceAccessorById(@NonNull final DeviceId id)
{
return deviceConfigPool.getAllAttributeCodes()
.stream()
.map(this::getDeviceAccessors)
.map(deviceAccessorsList -> deviceAccessorsList.getByIdOrNull(id))
.filter(Objects::nonNull)
.findFirst();
}
public @NonNull DeviceAccessorsList getDeviceAccessors(final AttributeCode attributeCode)
{
//noinspection DataFlowIssue
return cache.getOrLoad(attributeCode, this::createDeviceAccessorsList);
}
private DeviceAccessorsList createDeviceAccessorsList(final AttributeCode attributeCode)
{
final List<DeviceConfig> deviceConfigsForThisAttribute = deviceConfigPool.getDeviceConfigsForAttributeCode(attributeCode);
logger.info("Devices configs for attribute {}: {}", attributeCode, deviceConfigsForThisAttribute);
if (deviceConfigsForThisAttribute.isEmpty())
{
return DeviceAccessorsList.EMPTY;
}
final ImmutableList.Builder<DeviceAccessor> deviceAccessors = ImmutableList.builder();
final StringBuilder warningMessage = new StringBuilder();
for (final DeviceConfig deviceConfig : deviceConfigsForThisAttribute)
{
// trying to access the device and instantiate hooks.
final IDevice device;
final ImmutableList<BeforeAcquireValueHook> beforeHooks;
try
{
device = DeviceInstanceUtils.createAndConfigureDevice(deviceConfig);
beforeHooks = DeviceInstanceUtils.instantiateHooks(deviceConfig);
}
catch (final Exception e)
{
final String msg = String.format("Unable to access device identified by %s. Details:\n%s", deviceConfig, e.getLocalizedMessage());
logger.warn(msg + ". Skipped", e);
if (warningMessage.length() > 0)
{
warningMessage.append("\n");
}
warningMessage.append(msg);
continue;
} | final List<IDeviceRequest<ISingleValueResponse>> allRequestsFor = DeviceInstanceUtils.getAllRequestsFor(deviceConfig, attributeCode, ISingleValueResponse.class);
logger.info("Found these requests for {} and attribute {}: {}", deviceConfig, attributeCode, allRequestsFor);
// NOTE: usually we expect one element (maximum) in allRequestsFor
for (final IDeviceRequest<ISingleValueResponse> request : allRequestsFor)
{
final String deviceName = deviceConfig.getDeviceName();
final DeviceId deviceId = DeviceId.ofString(deviceName + "-" + attributeCode.getCode() + "-" + request.getClass().getSimpleName());
final DeviceAccessor deviceAccessor = DeviceAccessor.builder()
.id(deviceId)
.deviceConfig(deviceConfig)
.displayName(TranslatableStrings.anyLanguage(deviceName))
.device(device)
.request(request)
.beforeHooks(beforeHooks)
.build();
deviceAccessors.add(deviceAccessor);
}
}
return DeviceAccessorsList.of(deviceAccessors.build(), warningMessage.toString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceAccessorsHub.java | 1 |
请完成以下Java代码 | public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note; | }
@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(", orderId=").append(orderId);
sb.append(", operateMan=").append(operateMan);
sb.append(", createTime=").append(createTime);
sb.append(", orderStatus=").append(orderStatus);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderOperateHistory.java | 1 |
请完成以下Java代码 | public class WebsocketActiveSubscriptionsIndex
{
private final SetMultimap<WebsocketTopicName, WebsocketSubscriptionId> subscriptionIdsByTopicName = HashMultimap.create();
private final SetMultimap<WebsocketSessionId, WebsocketSubscriptionId> subscriptionIdsBySessionId = HashMultimap.create();
private final HashMap<WebsocketSubscriptionId, WebsocketTopicName> topicNamesBySubscriptionId = new HashMap<>();
public synchronized void addSubscription(
@NonNull final WebsocketSubscriptionId subscriptionId,
@NonNull final WebsocketTopicName topicName)
{
subscriptionIdsByTopicName.put(topicName, subscriptionId);
subscriptionIdsBySessionId.put(subscriptionId.getSessionId(), subscriptionId);
topicNamesBySubscriptionId.put(subscriptionId, topicName);
}
@Nullable
public synchronized WebsocketTopicName removeSubscriptionAndGetTopicName(@NonNull final WebsocketSubscriptionId subscriptionId)
{
final WebsocketTopicName topicName = topicNamesBySubscriptionId.remove(subscriptionId);
if (topicName != null)
{
subscriptionIdsByTopicName.removeAll(topicName);
}
return topicName;
}
@Nullable
public synchronized Set<WebsocketTopicName> removeSessionAndGetTopicNames(@NonNull final WebsocketSessionId sessionId)
{
final Set<WebsocketSubscriptionId> subscriptionIds = subscriptionIdsBySessionId.removeAll(sessionId);
if (subscriptionIds == null || subscriptionIds.isEmpty())
{ | return ImmutableSet.of();
}
final ImmutableSet.Builder<WebsocketTopicName> topicNames = ImmutableSet.builder();
for (final WebsocketSubscriptionId subscriptionId : subscriptionIds)
{
final WebsocketTopicName topicName = removeSubscriptionAndGetTopicName(subscriptionId);
if (topicName != null)
{
topicNames.add(topicName);
}
}
return topicNames.build();
}
public synchronized boolean hasSubscriptionsForTopicName(@NonNull final WebsocketTopicName topicName)
{
return subscriptionIdsByTopicName.containsKey(topicName);
}
public synchronized ImmutableSetMultimap<WebsocketTopicName, WebsocketSubscriptionId> getSubscriptionIdsByTopicName()
{
return ImmutableSetMultimap.copyOf(subscriptionIdsByTopicName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebsocketActiveSubscriptionsIndex.java | 1 |
请完成以下Java代码 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if (!validateCertificateChain(chain)) {
throw new CertificateException("Invalid Chain of X509 Certificates. ");
}
String clientDeviceCertValue = SslUtil.getCertificateString(chain[0]);
final String[] credentialsBodyHolder = new String[1];
CountDownLatch latch = new CountDownLatch(1);
try {
String certificateChain = SslUtil.getCertificateChainString(chain);
transportService.process(DeviceTransportType.MQTT, TransportProtos.ValidateOrCreateDeviceX509CertRequestMsg
.newBuilder().setCertificateChain(certificateChain).build(),
new TransportServiceCallback<>() {
@Override
public void onSuccess(ValidateDeviceCredentialsResponse msg) {
if (!StringUtils.isEmpty(msg.getCredentials())) {
credentialsBodyHolder[0] = msg.getCredentials();
}
latch.countDown();
}
@Override
public void onError(Throwable e) {
log.trace("Failed to process certificate chain: {}", certificateChain, e);
latch.countDown();
}
});
latch.await(10, TimeUnit.SECONDS);
if (!clientDeviceCertValue.equals(credentialsBodyHolder[0])) {
log.debug("Failed to find credentials for device certificate chain: {}", chain);
if (chain.length == 1) {
throw new CertificateException("Invalid Device Certificate");
} else {
throw new CertificateException("Invalid Chain of X509 Certificates");
}
}
} catch (Exception e) { | log.error(e.getMessage(), e);
}
}
private boolean validateCertificateChain(X509Certificate[] chain) {
try {
if (chain.length > 1) {
X509Certificate leafCert = chain[0];
for (int i = 1; i < chain.length; i++) {
X509Certificate intermediateCert = chain[i];
leafCert.verify(intermediateCert.getPublicKey());
leafCert = intermediateCert;
}
}
return true;
} catch (Exception e) {
return false;
}
}
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\MqttSslHandlerProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult delete(@PathVariable Long id) {
int count = resourceService.delete(id);
dynamicSecurityMetadataSource.clearDataSource();
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("分页模糊查询后台资源")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<UmsResource>> list(@RequestParam(required = false) Long categoryId,
@RequestParam(required = false) String nameKeyword, | @RequestParam(required = false) String urlKeyword,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<UmsResource> resourceList = resourceService.list(categoryId,nameKeyword, urlKeyword, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(resourceList));
}
@ApiOperation("查询所有后台资源")
@RequestMapping(value = "/listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<UmsResource>> listAll() {
List<UmsResource> resourceList = resourceService.listAll();
return CommonResult.success(resourceList);
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsResourceController.java | 2 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e)
{
MQuery query = null;
if (e.getSource() == m_active)
{
query = new MQuery("");
String where = "(" + m_where + ") AND Processed='N'";
query.addRestriction(where);
}
else if (e.getSource() == m_all)
{
query = new MQuery("");
query.addRestriction(m_where.toString());
}
//
final AdWindowId adWindowId = AdWindowId.ofRepoId(232); // 232=all - 201=my
AWindow frame = new AWindow();
if (!frame.initWindow(adWindowId, query))
{
return;
}
AEnv.addToWindowManager(frame);
// New - set Table/Record
if (e.getSource() == m_new)
{
GridTab tab = frame.getAPanel().getCurrentTab();
tab.dataNew(DataNewCopyMode.NoCopy);
tab.setValue("AD_Table_ID", new Integer(m_AD_Table_ID));
tab.setValue("Record_ID", new Integer(m_Record_ID));
//
if (m_C_BPartner_ID != 0)
{
tab.setValue("C_BPartner_ID", new Integer(m_C_BPartner_ID));
}
//
if (m_AD_Table_ID == bpartnerTableId)
{
tab.setValue("C_BPartner_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(I_AD_User.class))
{
tab.setValue("AD_User_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(I_C_Project.class))
{
tab.setValue("C_Project_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(MAsset.class))
{
tab.setValue("A_Asset_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(I_C_Order.class))
{
tab.setValue("C_Order_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(I_C_Invoice.class))
{
tab.setValue("C_Invoice_ID", new Integer(m_Record_ID)); | }
else if (m_AD_Table_ID == getTableId(I_M_Product.class))
{
tab.setValue("M_Product_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(I_C_Payment.class))
{
tab.setValue("C_Payment_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(I_M_InOut.class))
{
tab.setValue("M_InOut_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == MRMA.Table_ID)
{
tab.setValue("M_RMA_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == MCampaign.Table_ID)
{
tab.setValue("C_Campaign_ID", new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(I_R_Request.class))
{
tab.setValue(MRequest.COLUMNNAME_R_RequestRelated_ID, new Integer(m_Record_ID));
}
else if (m_AD_Table_ID == getTableId(I_C_OrderLine.class))
{
MOrderLine oLine = new MOrderLine(Env.getCtx(), m_Record_ID, null);
if (oLine != null)
{
tab.setValue(MOrderLine.COLUMNNAME_C_Order_ID, new Integer(oLine.getC_Order_ID()));
}
}
}
AEnv.showCenterScreen(frame);
frame = null;
} // actionPerformed
} // ARequest | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ARequest.java | 1 |
请完成以下Java代码 | public String getTenantId() {
return tenantId;
}
public String getCreateUserId() {
return createUserId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(final Date startTime) {
this.startTime = startTime;
}
public Date getExecutionStartTime() {
return executionStartTime;
}
public void setExecutionStartTime(final Date executionStartTime) {
this.executionStartTime = executionStartTime;
}
public static BatchDto fromBatch(Batch batch) {
BatchDto dto = new BatchDto();
dto.id = batch.getId();
dto.type = batch.getType();
dto.totalJobs = batch.getTotalJobs(); | dto.jobsCreated = batch.getJobsCreated();
dto.batchJobsPerSeed = batch.getBatchJobsPerSeed();
dto.invocationsPerBatchJob = batch.getInvocationsPerBatchJob();
dto.seedJobDefinitionId = batch.getSeedJobDefinitionId();
dto.monitorJobDefinitionId = batch.getMonitorJobDefinitionId();
dto.batchJobDefinitionId = batch.getBatchJobDefinitionId();
dto.suspended = batch.isSuspended();
dto.tenantId = batch.getTenantId();
dto.createUserId = batch.getCreateUserId();
dto.startTime = batch.getStartTime();
dto.executionStartTime = batch.getExecutionStartTime();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchDto.java | 1 |
请完成以下Java代码 | public boolean isOnlyStages() {
return onlyStages;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public boolean isIncludeLocalVariables() {
return includeLocalVariables;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
} | public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public List<List<String>> getSafeCaseInstanceIds() {
return safeCaseInstanceIds;
}
public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeCaseInstanceIds = safeProcessInstanceIds;
}
public Collection<String> getCaseInstanceIds() {
return caseInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricPlanItemInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public void setAccessTokenCustomizer(OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer) {
Assert.notNull(accessTokenCustomizer, "accessTokenCustomizer cannot be null");
this.accessTokenCustomizer = accessTokenCustomizer;
}
/**
* Sets the {@link Clock} used when obtaining the current instant via
* {@link Clock#instant()}.
* @param clock the {@link Clock} used when obtaining the current instant via
* {@link Clock#instant()}
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
private static final class OAuth2AccessTokenClaims extends OAuth2AccessToken implements ClaimAccessor {
private final Map<String, Object> claims; | private OAuth2AccessTokenClaims(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt,
Set<String> scopes, Map<String, Object> claims) {
super(tokenType, tokenValue, issuedAt, expiresAt, scopes);
this.claims = claims;
}
@Override
public Map<String, Object> getClaims() {
return this.claims;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2AccessTokenGenerator.java | 1 |
请完成以下Java代码 | public Iterator<String> iterator() {
return this.candidates.iterator();
}
/**
* Returns the list of loaded import candidates.
* @return the list of import candidates
*/
public List<String> getCandidates() {
return this.candidates;
}
/**
* Loads the names of import candidates from the classpath. The names of the import
* candidates are stored in files named
* {@code META-INF/spring/full-qualified-annotation-name.imports} on the classpath.
* Every line contains the full qualified name of the candidate class. Comments are
* supported using the # character.
* @param annotation annotation to load
* @param classLoader class loader to use for loading
* @return list of names of annotated classes
*/
public static ImportCandidates load(Class<?> annotation, @Nullable ClassLoader classLoader) {
Assert.notNull(annotation, "'annotation' must not be null");
ClassLoader classLoaderToUse = decideClassloader(classLoader);
String location = String.format(LOCATION, annotation.getName());
Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location);
List<String> importCandidates = new ArrayList<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
importCandidates.addAll(readCandidateConfigurations(url));
}
return new ImportCandidates(importCandidates);
}
private static ClassLoader decideClassloader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
return ImportCandidates.class.getClassLoader();
}
return classLoader;
}
private static Enumeration<URL> findUrlsInClasspath(ClassLoader classLoader, String location) {
try {
return classLoader.getResources(location);
}
catch (IOException ex) { | throw new IllegalArgumentException("Failed to load configurations from location [" + location + "]", ex);
}
}
private static List<String> readCandidateConfigurations(URL url) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new UrlResource(url).getInputStream(), StandardCharsets.UTF_8))) {
List<String> candidates = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
line = stripComment(line);
line = line.trim();
if (line.isEmpty()) {
continue;
}
candidates.add(line);
}
return candidates;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load configurations from location [" + url + "]", ex);
}
}
private static String stripComment(String line) {
int commentStart = line.indexOf(COMMENT_START);
if (commentStart == -1) {
return line;
}
return line.substring(0, commentStart);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\annotation\ImportCandidates.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 String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
} | public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaFullJoins\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public void setEventOutParameters(List<IOParameter> eventOutParameters) {
this.eventOutParameters = eventOutParameters;
}
@Override
public SendEventServiceTask clone() {
SendEventServiceTask clone = new SendEventServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(SendEventServiceTask otherElement) {
super.setValues(otherElement);
setEventType(otherElement.getEventType());
setTriggerEventType(otherElement.getTriggerEventType());
setSendSynchronously(otherElement.isSendSynchronously()); | eventInParameters = new ArrayList<>();
if (otherElement.getEventInParameters() != null && !otherElement.getEventInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getEventInParameters()) {
eventInParameters.add(parameter.clone());
}
}
eventOutParameters = new ArrayList<>();
if (otherElement.getEventOutParameters() != null && !otherElement.getEventOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getEventOutParameters()) {
eventOutParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SendEventServiceTask.java | 1 |
请完成以下Java代码 | public String getVersion() {
return version;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.version
*
* @param version the value for rule.version
*
* @mbggenerated
*/
public void setVersion(String version) {
this.version = version == null ? null : version.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rule.content
*
* @return the value of rule.content
*
* @mbggenerated
*/
public String getContent() {
return content;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.content
*
* @param content the value for rule.content
*
* @mbggenerated
*/
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rule.create_time
*
* @return the value of rule.create_time
*
* @mbggenerated
*/
public Date getCreateTime() {
return createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.create_time
*
* @param createTime the value for rule.create_time
*
* @mbggenerated
*/
public void setCreateTime(Date createTime) { | this.createTime = createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rule.update_time
*
* @return the value of rule.update_time
*
* @mbggenerated
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.update_time
*
* @param updateTime the value for rule.update_time
*
* @mbggenerated
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
} | repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\domain\model\Rule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserSessionRestController
{
public static final String ENDPOINT = WebConfig.ENDPOINT_ROOT + "/userSession";
private static final String SYSCONFIG_SETTINGS_PREFIX = "webui.frontend.";
private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
@NonNull private final UserSession userSession;
@NonNull private final UserSessionRepository userSessionRepo;
@NonNull private final DocumentCollection documentCollection;
@NonNull private final WorkplaceService workplaceService;
@GetMapping
public JSONUserSession getAll()
{
final Map<String, String> settings = sysConfigBL.getValuesForPrefix(
SYSCONFIG_SETTINGS_PREFIX,
true,
ClientAndOrgId.ofClientAndOrg(userSession.getClientId(), userSession.getOrgId()));
return new JSONUserSession(userSession, settings);
}
@PutMapping("/language")
public JSONLookupValue setLanguage(@RequestBody final JSONLookupValue value)
{
final String adLanguage = value.getKey();
userSessionRepo.setAD_Language(userSession.getLoggedUserId(), adLanguage);
documentCollection.cacheReset(false); // don't evict unsaved documents from the cache, because they would be lost entirely
return getLanguage();
}
@GetMapping("/language")
public JSONLookupValue getLanguage()
{
final Language language = userSession.getLanguage();
return JSONLookupValue.of(language.getAD_Language(), language.getName());
}
@GetMapping("/workplace")
public JsonGetWorkplaceResponse getWorkplace(@RequestParam(name = "includeAvailable", required = false) final boolean includeAvailable)
{
userSession.assertLoggedIn();
final boolean isWorkplacesEnabled = userSession.isWorkplacesEnabled();
if (isWorkplacesEnabled)
{
final JsonGetWorkplaceResponseBuilder builder = JsonGetWorkplaceResponse.builder().workplacesEnabled(true);
userSession.getWorkplace() | .map(UserSessionRestController::toJSONLookupValue)
.ifPresent(builder::currentWorkplace);
if (includeAvailable)
{
builder.available(workplaceService.getAllActive()
.stream()
.map(UserSessionRestController::toJSONLookupValue)
.sorted(Comparator.comparing(JSONLookupValue::getCaption))
.collect(ImmutableList.toImmutableList()));
}
return builder.build();
}
else
{
return JsonGetWorkplaceResponse.NOT_ENABLED;
}
}
private static JSONLookupValue toJSONLookupValue(@NonNull Workplace workplace)
{
return JSONLookupValue.of(workplace.getId(), workplace.getName());
}
@PutMapping("/workplace")
public void setWorkplace(@RequestBody @NonNull final JsonChangeWorkplaceRequest request)
{
userSession.assertLoggedIn();
if (!userSession.isWorkplacesEnabled())
{
throw new AdempiereException("Workplaces not enabled");
}
workplaceService.assignWorkplace(WorkplaceAssignmentCreateRequest.builder()
.workplaceId(request.getWorkplaceId())
.userId(userSession.getLoggedUserId())
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserSessionRestController.java | 2 |
请完成以下Java代码 | private boolean applies(final List<I_C_Flatrate_Term> flatrateTermsForInvoiceId)
{
if (flatrateTermsForInvoiceId.isEmpty())
{
return false;
}
if (containsNewTerm(flatrateTermsForInvoiceId))
{
return false;
}
return true;
}
private boolean containsNewTerm(@NonNull final List<I_C_Flatrate_Term> flatrateTermsForInvoiceId)
{
for (final I_C_Flatrate_Term term : flatrateTermsForInvoiceId)
{
if (isNewTerm(term))
{
return true;
}
}
return false;
}
private boolean isNewTerm(@NonNull final I_C_Flatrate_Term term)
{
return Objects.equals(term.getMasterStartDate(), term.getStartDate());
}
private List<I_C_Flatrate_Term> retrieveFlatrateTermsForInvoiceId(@NonNull final InvoiceId invoiceId)
{
return invoiceId2flatrateTerms.getOrLoad(invoiceId, () -> retrieveFlatrateTermsForInvoiceId0(invoiceId));
} | private List<I_C_Flatrate_Term> retrieveFlatrateTermsForInvoiceId0(@NonNull final InvoiceId invoiceId)
{
final List<I_C_Flatrate_Term> flatrateTerms = Services
.get(IQueryBL.class)
.createQueryBuilder(I_C_InvoiceLine.class)
.addEqualsFilter(I_C_InvoiceLine.COLUMN_C_Invoice_ID, invoiceId)
.andCollectChildren(I_C_Invoice_Line_Alloc.COLUMN_C_InvoiceLine_ID)
.andCollect(I_C_Invoice_Line_Alloc.COLUMN_C_Invoice_Candidate_ID)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_AD_Table_ID, getTableId(I_C_Flatrate_Term.class))
.andCollect(I_C_Invoice_Candidate.COLUMNNAME_Record_ID, I_C_Flatrate_Term.class)
.create()
.list();
return flatrateTerms;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\dunning\ContractBasedInvoiceDueDateProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class EnableRedisKeyspaceNotificationsInitializer implements InitializingBean {
private final RedisConnectionFactory connectionFactory;
private final ConfigureRedisAction configure;
EnableRedisKeyspaceNotificationsInitializer(RedisConnectionFactory connectionFactory,
ConfigureRedisAction configure) {
this.connectionFactory = connectionFactory;
this.configure = configure;
}
@Override
public void afterPropertiesSet() {
if (this.configure == ConfigureRedisAction.NO_OP) {
return;
} | RedisConnection connection = this.connectionFactory.getConnection();
try {
this.configure.configure(connection);
}
finally {
try {
connection.close();
}
catch (Exception ex) {
LogFactory.getLog(getClass()).error("Error closing RedisConnection", ex);
}
}
}
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\RedisIndexedHttpSessionConfiguration.java | 2 |
请完成以下Java代码 | private static <T> T getContextualReference(BeanManager bm, Set<Bean<?>> beans, Class<?> type) {
if (beans == null || beans.size() == 0) {
return null;
}
// if we would resolve to multiple beans then BeanManager#resolve would throw an AmbiguousResolutionException
Bean<?> bean = bm.resolve(beans);
if (bean == null) {
return null;
} else {
CreationalContext<?> creationalContext = bm.createCreationalContext(bean);
// if we obtain a contextual reference to a @Dependent scope bean, make sure it is released
if(isDependentScoped(bean)) {
releaseOnContextClose(creationalContext, bean);
}
return (T) bm.getReference(bean, type, creationalContext);
} | }
private static boolean isDependentScoped(Bean<?> bean) {
return Dependent.class.equals(bean.getScope());
}
private static void releaseOnContextClose(CreationalContext<?> creationalContext, Bean<?> bean) {
CommandContext commandContext = Context.getCommandContext();
if(commandContext != null) {
commandContext.registerCommandContextListener(new CreationalContextReleaseListener(creationalContext));
} else {
LOG.warning("Obtained instance of @Dependent scoped bean "+bean +" outside of process engine command context. "
+ "Bean instance will not be destroyed. This is likely to create a memory leak. Please use a normal scope like @ApplicationScoped for this bean.");
}
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\util\ProgrammaticBeanLookup.java | 1 |
请完成以下Java代码 | public CostDetailCreateRequest withQtyZero()
{
return withQty(qty.toZero());
}
public CostDetailBuilder toCostDetailBuilder()
{
final CostDetailBuilder costDetail = CostDetail.builder()
.clientId(getClientId())
.orgId(getOrgId())
.acctSchemaId(getAcctSchemaId())
.productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId())
//
.amtType(getAmtType()) | .amt(getAmt())
.qty(getQty())
//
.documentRef(getDocumentRef())
.description(getDescription())
.dateAcct(getDate());
if (isExplicitCostElement())
{
costDetail.costElementId(getCostElementId());
}
return costDetail;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateRequest.java | 1 |
请完成以下Java代码 | default void setBatchListener(boolean batchListener) {
}
/**
* Whether this endpoint is for a batch listener.
* @return {@link Boolean#TRUE} if batch.
* @since 3.0
*/
@Nullable
Boolean getBatchListener();
/**
* Set a {@link BatchingStrategy} to use when debatching messages.
* @param batchingStrategy the batching strategy.
* @since 2.2
* @see #setBatchListener(boolean)
*/
default void setBatchingStrategy(BatchingStrategy batchingStrategy) {
}
/**
* Return this endpoint's batching strategy, or null.
* @return the strategy.
* @since 2.4.7
*/
default @Nullable BatchingStrategy getBatchingStrategy() {
return null;
}
/**
* Override the container factory's {@link AcknowledgeMode}.
* @return the acknowledgment mode.
* @since 2.2
*/
default @Nullable AcknowledgeMode getAckMode() {
return null;
}
/**
* Return a {@link ReplyPostProcessor} to post process a reply message before it is | * sent.
* @return the post processor.
* @since 2.2.5
*/
default @Nullable ReplyPostProcessor getReplyPostProcessor() {
return null;
}
/**
* Get the reply content type.
* @return the content type.
* @since 2.3
*/
default @Nullable String getReplyContentType() {
return null;
}
/**
* Return whether the content type set by a converter prevails or not.
* @return false to always apply the reply content type.
* @since 2.3
*/
default boolean isConverterWinsContentType() {
return true;
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\RabbitListenerEndpoint.java | 1 |
请完成以下Java代码 | public class CronTimer {
protected final Cron cron;
public CronTimer(final Cron cron) {
this.cron = cron;
}
public Date getDueDate(final Date afterTime) {
long fromEpochMilli = afterTime.getTime();
final var next = ExecutionTime.forCron(cron)
.nextExecution(ZonedDateTime.ofInstant(Instant.ofEpochMilli(fromEpochMilli), ZoneId.systemDefault()))
.map(ZonedDateTime::toInstant)
.map(Instant::toEpochMilli); | return new Date(next.orElse(fromEpochMilli));
}
public static CronTimer parse(final String text) throws ParseException {
try {
final var cron =
new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.SPRING53))
.parse(text);
return new CronTimer(cron);
} catch (final IllegalArgumentException | NullPointerException ex) {
throw new ParseException(ex.getMessage(), 0);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\calendar\CronTimer.java | 1 |
请完成以下Java代码 | public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
}
// Cache listeners. Currently not yet exposed (only programmatically for the | // moment)
// Experimental stuff!
public static interface LDAPGroupCacheListener {
void cacheHit(String userId);
void cacheMiss(String userId);
void cacheEviction(String userId);
void cacheExpired(String userId);
}
} | repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\LDAPGroupCache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MyAdditionalEntityManagerFactoryConfiguration {
@Qualifier("second")
@Bean(defaultCandidate = false)
@ConfigurationProperties("app.jpa")
public JpaProperties secondJpaProperties() {
return new JpaProperties();
}
@Qualifier("second")
@Bean(defaultCandidate = false)
public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory(@Qualifier("second") DataSource dataSource,
@Qualifier("second") JpaProperties jpaProperties) {
EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(jpaProperties);
return builder.dataSource(dataSource).packages(Order.class).persistenceUnit("second").build();
}
private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties jpaProperties) {
JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(jpaProperties);
Function<DataSource, Map<String, ?>> jpaPropertiesFactory = (dataSource) -> createJpaProperties(dataSource, | jpaProperties.getProperties());
return new EntityManagerFactoryBuilder(jpaVendorAdapter, jpaPropertiesFactory, null);
}
private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) {
// ... map JPA properties as needed
return new HibernateJpaVendorAdapter();
}
private Map<String, ?> createJpaProperties(DataSource dataSource, Map<String, ?> existingProperties) {
Map<String, ?> jpaProperties = new LinkedHashMap<>(existingProperties);
// ... map JPA properties that require the DataSource (e.g. DDL flags)
return jpaProperties;
}
} | repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\howto\dataaccess\usemultipleentitymanagers\MyAdditionalEntityManagerFactoryConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Page<Article> getArticleFavoritedByUsername(UserName username, Pageable pageable) {
return userFindService.findByUsername(username)
.map(user -> articleRepository.findAllByUserFavoritedContains(user, pageable)
.map(article -> article.updateFavoriteByUser(user)))
.orElse(Page.empty());
}
@Transactional(readOnly = true)
public Page<Article> getArticlesByAuthorName(String authorName, Pageable pageable) {
return articleRepository.findAllByAuthorProfileUserName(new UserName(authorName), pageable);
}
@Transactional(readOnly = true)
public Page<Article> getArticlesByTag(String tagValue, Pageable pageable) {
return tagService.findByValue(tagValue)
.map(tag -> articleRepository.findAllByContentsTagsContains(tag, pageable))
.orElse(Page.empty());
}
@Override
@Transactional(readOnly = true)
public Optional<Article> getArticleBySlug(String slug) {
return articleRepository.findFirstByContentsTitleSlug(slug);
}
@Transactional
public Article updateArticle(long userId, String slug, ArticleUpdateRequest request) {
return mapIfAllPresent(userFindService.findById(userId), getArticleBySlug(slug),
(user, article) -> user.updateArticle(article, request))
.orElseThrow(NoSuchElementException::new);
}
@Transactional | public Article favoriteArticle(long userId, String articleSlugToFavorite) {
return mapIfAllPresent(
userFindService.findById(userId), getArticleBySlug(articleSlugToFavorite),
User::favoriteArticle)
.orElseThrow(NoSuchElementException::new);
}
@Transactional
public Article unfavoriteArticle(long userId, String articleSlugToUnFavorite) {
return mapIfAllPresent(
userFindService.findById(userId), getArticleBySlug(articleSlugToUnFavorite),
User::unfavoriteArticle)
.orElseThrow(NoSuchElementException::new);
}
@Transactional
public void deleteArticleBySlug(long userId, String slug) {
userFindService.findById(userId)
.ifPresentOrElse(user -> articleRepository.deleteArticleByAuthorAndContentsTitleSlug(user, slug),
() -> {throw new NoSuchElementException();});
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\ArticleService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BlogsController {
private final ChatClient chatClient;
private final VectorStore vectorStore;
public BlogsController(ChatClient.Builder chatClientBuilder, EmbeddingModel embeddingModel) throws IOException {
this.chatClient = chatClientBuilder.build();
this.vectorStore = SimpleVectorStore.builder(embeddingModel).build();
initContext();
}
private void initContext() throws IOException {
List<Document> documents = Files.readAllLines(Path.of("src/main/resources/articles.txt"))
.stream()
.map(Document::new)
.toList();
vectorStore.add(documents);
}
@GetMapping("v1")
String askQuestion(@RequestParam(name = "question") String question) {
return chatClient.prompt()
.user(question) | .call()
.content();
}
record Article(String title, Set<String> tags) {
}
@GetMapping("v2")
List<Article> askQuestionAndRetrieveArticles(@RequestParam(name = "question") String question) {
return chatClient.prompt()
.user(question)
.call()
.entity(new ParameterizedTypeReference<List<Article>>() {});
}
@GetMapping("v3")
List<Article> askQuestionWithContext(@RequestParam(name = "question") String question) {
return chatClient.prompt()
.advisors(new QuestionAnswerAdvisor(vectorStore, SearchRequest.builder().build()))
.user(question)
.call()
.entity(new ParameterizedTypeReference<List<Article>>() {});
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springai\chatclient\rest\BlogsController.java | 2 |
请完成以下Java代码 | private List<I_M_HU_PI_Item_Product> getTUPIItemProducts(final @NonNull FinishedGoodsReceiveLine finishedGoodsReceiveLine, final @Nullable BPartnerId customerId)
{
return huPIItemProductDAO.retrieveTUs(
Env.getCtx(),
finishedGoodsReceiveLine.getProductId(),
customerId,
false);
}
private HuPackingInstructionsId getTUPackingInstructionsId(final I_M_HU_PI_Item_Product tuPIItemProduct)
{
final HuPackingInstructionsItemId tuPackingInstructionsItemId = HuPackingInstructionsItemId.ofRepoId(tuPIItemProduct.getM_HU_PI_Item_ID());
return handlingUnitsBL.getPackingInstructionsId(tuPackingInstructionsItemId);
} | private QtyTU computeQtyTUsRequired(final @NonNull FinishedGoodsReceiveLine finishedGoodsReceiveLine, final I_M_HU_PI_Item_Product tuPIItemProduct)
{
final UomId uomId = UomId.ofRepoId(tuPIItemProduct.getC_UOM_ID());
final Quantity qtyCusPerTU = Quantitys.of(tuPIItemProduct.getQty(), uomId);
final Quantity qtyCUs = uomConversionBL.convertQuantityTo(finishedGoodsReceiveLine.getQtyToReceive(), finishedGoodsReceiveLine.getProductId(), uomId);
return QtyTU.ofBigDecimal(qtyCUs.toBigDecimal().divide(qtyCusPerTU.toBigDecimal(), 0, RoundingMode.UP));
}
@Override
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity)
{
return wfActivity.getStatus();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\generateHUQRCodes\GenerateHUQRCodesActivityHandler.java | 1 |
请完成以下Java代码 | public ContextPath newChild(@NonNull final DocumentEntityDescriptor entityDescriptor)
{
return newChild(ContextPathElement.ofNameAndId(
extractName(entityDescriptor),
AdTabId.toRepoId(entityDescriptor.getAdTabIdOrNull())
));
}
private ContextPath newChild(@NonNull final ContextPathElement element)
{
return new ContextPath(ImmutableList.<ContextPathElement>builder()
.addAll(elements)
.add(element)
.build());
}
public AdWindowId getAdWindowId()
{
return AdWindowId.ofRepoId(elements.get(0).getId());
}
@Override
public int compareTo(@NonNull final ContextPath other)
{
return toJson().compareTo(other.toJson());
}
}
@Value
class ContextPathElement
{
@NonNull String name;
int id;
@JsonCreator
public static ContextPathElement ofJson(@NonNull final String json)
{
try
{
final int idx = json.indexOf("/");
if (idx > 0)
{
String name = json.substring(0, idx);
int id = Integer.parseInt(json.substring(idx + 1)); | return new ContextPathElement(name, id);
}
else
{
return new ContextPathElement(json, -1);
}
}
catch (final Exception ex)
{
throw new AdempiereException("Failed parsing: " + json, ex);
}
}
public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);}
public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson() {return id > 0 ? name + "/" + id : name;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java | 1 |
请完成以下Java代码 | public boolean isExecutable() {
return true;
}
}
/**
* Executable expanded archive layout.
*/
public static class Expanded extends Jar {
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.launch.PropertiesLauncher";
}
}
/**
* No layout.
*/
public static class None extends Jar {
@Override
public @Nullable String getLauncherClassName() {
return null;
}
@Override
public boolean isExecutable() {
return false;
}
}
/**
* Executable WAR layout.
*/
public static class War implements Layout {
private static final Map<LibraryScope, String> SCOPE_LOCATION;
static {
Map<LibraryScope, String> locations = new HashMap<>();
locations.put(LibraryScope.COMPILE, "WEB-INF/lib/"); | locations.put(LibraryScope.CUSTOM, "WEB-INF/lib/");
locations.put(LibraryScope.RUNTIME, "WEB-INF/lib/");
locations.put(LibraryScope.PROVIDED, "WEB-INF/lib-provided/");
SCOPE_LOCATION = Collections.unmodifiableMap(locations);
}
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.launch.WarLauncher";
}
@Override
public @Nullable String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) {
return SCOPE_LOCATION.get(scope);
}
@Override
public String getClassesLocation() {
return "WEB-INF/classes/";
}
@Override
public String getClasspathIndexFileLocation() {
return "WEB-INF/classpath.idx";
}
@Override
public String getLayersIndexFileLocation() {
return "WEB-INF/layers.idx";
}
@Override
public boolean isExecutable() {
return true;
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Layouts.java | 1 |
请完成以下Java代码 | public boolean isExpanded()
{
return expanded;
}
@Override
public void setExpanded(final boolean expanded)
{
if (this.expanded == expanded)
{
return;
}
this.expanded = expanded;
findPanel.setVisible(expanded);
findPanel.setEnabled(expanded);
_pcs.firePropertyChange(PROPERTY_Expanded, !expanded, expanded);
}
@Override
public boolean isFocusable()
{
return findPanel.isFocusable();
}
@Override
public void requestFocus()
{
findPanel.requestFocus();
}
@Override | public boolean requestFocusInWindow()
{
return findPanel.requestFocusInWindow();
}
private final synchronized PropertyChangeSupport getPropertyChangeSupport()
{
if (_pcs == null)
{
_pcs = new PropertyChangeSupport(this);
}
return _pcs;
}
@Override
public void runOnExpandedStateChange(final Runnable runnable)
{
Check.assumeNotNull(runnable, "runnable not null");
getPropertyChangeSupport().addPropertyChangeListener(PROPERTY_Expanded, new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
runnable.run();
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_EmbeddedPanel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
@GetMapping("/list")
@ApiOperation(value = "查询用户列表", notes = "目前仅仅是作为测试,所以返回用户全列表")
public List<UserVO> list() {
// 查询列表
List<UserVO> result = new ArrayList<>();
result.add(new UserVO().setId(1).setUsername("yudaoyuanma"));
result.add(new UserVO().setId(2).setUsername("woshiyutou"));
result.add(new UserVO().setId(3).setUsername("chifanshuijiao"));
// 返回列表
return result;
}
@GetMapping("/get")
@ApiOperation("获得指定用户编号的用户")
@ApiImplicitParam(name = "id", value = "用户编号", paramType = "query", dataTypeClass = Integer.class, required = true, example = "1024")
public UserVO get(@RequestParam("id") Integer id) {
// 查询并返回用户
return new UserVO().setId(id).setUsername(UUID.randomUUID().toString());
}
@PostMapping("add")
@ApiOperation("添加用户")
public Integer add(UserAddDTO addDTO) {
// 插入用户记录,返回编号 | Integer returnId = UUID.randomUUID().hashCode();
// 返回用户编号
return returnId;
}
@PostMapping("/update")
@ApiOperation("更新指定用户编号的用户")
public Boolean update(UserUpdateDTO updateDTO) {
// 更新用户记录
Boolean success = true;
// 返回更新是否成功
return success;
}
@PostMapping("/delete")
@ApiOperation(value = "删除指定用户编号的用户")
@ApiImplicitParam(name = "id", value = "用户编号", paramType = "query", dataTypeClass = Integer.class, required = true, example = "1024")
public Boolean delete(@RequestParam("id") Integer id) {
// 删除用户记录
Boolean success = false;
// 返回是否更新成功
return success;
}
} | repos\SpringBoot-Labs-master\lab-24\lab-24-apidoc-swagger\src\main\java\cn\iocoder\springboot\lab24\apidoc\controller\UserController.java | 2 |
请完成以下Java代码 | public int compare (Object o1, Object o2)
{
// Get Objects to compare
Object cmp1 = o1;
if (o1 instanceof MSort)
cmp1 = ((MSort)o1).data;
if (cmp1 instanceof NamePair)
cmp1 = ((NamePair)cmp1).getName();
Object cmp2 = o2;
if (o2 instanceof MSort)
cmp2 = ((MSort)o2).data;
if (cmp2 instanceof NamePair)
cmp2 = ((NamePair)cmp2).getName();
// Comparing Null values
if (cmp1 == null)
{
if (cmp2 == null)
return 0;
return -1 * m_multiplier;
}
if (cmp2 == null)
return 1 * m_multiplier;
/**
* compare different data types
*/
// String
if (cmp1 instanceof String && cmp2 instanceof String)
{
return m_collator.compare(cmp1, cmp2) * m_multiplier; // teo_sarca [ 1672820 ]
}
// Date
else if (cmp1 instanceof Timestamp && cmp2 instanceof Timestamp)
{
Timestamp t = (Timestamp)cmp1;
return t.compareTo((Timestamp)cmp2) * m_multiplier;
}
// BigDecimal
else if (cmp1 instanceof BigDecimal && cmp2 instanceof BigDecimal)
{
BigDecimal d = (BigDecimal)cmp1;
return d.compareTo((BigDecimal)cmp2) * m_multiplier;
}
// Integer
else if (cmp1 instanceof Integer && cmp2 instanceof Integer)
{
Integer d = (Integer)cmp1;
return d.compareTo((Integer)cmp2) * m_multiplier;
}
// Double
else if (cmp1 instanceof Double && cmp2 instanceof Double)
{
Double d = (Double)cmp1;
return d.compareTo((Double)cmp2) * m_multiplier;
}
// Convert to string value
String s = cmp1.toString(); | return m_collator.compare(s, cmp2.toString()) * m_multiplier; // teo_sarca [ 1672820 ]
} // compare
/**
* Equal (based on data, ignores index)
* @param obj object
* @return true if equal
*/
@Override
public boolean equals (Object obj)
{
if (obj instanceof MSort)
{
MSort ms = (MSort)obj;
if (data == ms.data)
return true;
}
return false;
} // equals
/**
* String Representation
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("MSort[");
sb.append("Index=").append(index).append(",Data=").append(data);
sb.append("]");
return sb.toString();
} // toString
} // MSort | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\MSort.java | 1 |
请完成以下Java代码 | public Builder setRecordId(@Nullable final DocumentId documentId)
{
recordIds = documentId != null
? ImmutableSet.of(documentId)
: ImmutableSet.of();
return this;
}
public Builder setRecordIds(@Nullable final Collection<DocumentId> documentIds)
{
recordIds = documentIds != null
? ImmutableSet.copyOf(documentIds)
: ImmutableSet.of();
return this;
}
public Builder setParentDocument(final Document parentDocument)
{
this.parentDocument = parentDocument;
return this;
}
public Builder noSorting()
{
_noSorting = true;
_orderBys = null;
return this;
}
public boolean isNoSorting()
{
return _noSorting;
}
public Builder addOrderBy(@NonNull final DocumentQueryOrderBy orderBy)
{
Check.assume(!_noSorting, "sorting not disabled for {}", this);
if (_orderBys == null)
{
_orderBys = new ArrayList<>();
}
_orderBys.add(orderBy);
return this;
}
public Builder setOrderBys(final DocumentQueryOrderByList orderBys)
{
if (orderBys == null || orderBys.isEmpty())
{
_orderBys = null;
}
else
{
_orderBys = new ArrayList<>(orderBys.toList());
}
return this;
}
private DocumentQueryOrderByList getOrderBysEffective() | {
return _noSorting
? DocumentQueryOrderByList.EMPTY
: DocumentQueryOrderByList.ofList(_orderBys);
}
public Builder setFirstRow(final int firstRow)
{
this.firstRow = firstRow;
return this;
}
public Builder setPageLength(final int pageLength)
{
this.pageLength = pageLength;
return this;
}
public Builder setExistingDocumentsSupplier(final Function<DocumentId, Document> existingDocumentsSupplier)
{
this.existingDocumentsSupplier = existingDocumentsSupplier;
return this;
}
public Builder setChangesCollector(IDocumentChangesCollector changesCollector)
{
this.changesCollector = changesCollector;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQuery.java | 1 |
请完成以下Java代码 | private String tableToJava(String tableName, String tablePrefix) {
if (StrUtil.isNotBlank(tablePrefix)) {
tableName = tableName.replaceFirst(tablePrefix, "");
}
return columnToJava(tableName);
}
/**
* 获取配置信息
*/
private Props getConfig(String fileName) {
Props props = new Props(fileName);
props.autoLoad(true);
return props;
}
/**
* 获取文件名
*/
private String getFileName(String template, String className, String packageName, String moduleName) {
// 包路径
String packagePath = GenConstants.SIGNATURE + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator;
// 资源路径
String resourcePath = GenConstants.SIGNATURE + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
// api路径
String apiPath = GenConstants.SIGNATURE + File.separator + "api" + File.separator;
if (StrUtil.isNotBlank(packageName)) {
packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
}
if (template.contains(ENTITY_JAVA_VM)) { | return packagePath + "entity" + File.separator + className + ".java";
}
if (template.contains(MAPPER_JAVA_VM)) {
return packagePath + "mapper" + File.separator + className + "Mapper.java";
}
if (template.contains(SERVICE_JAVA_VM)) {
return packagePath + "service" + File.separator + className + "Service.java";
}
if (template.contains(SERVICE_IMPL_JAVA_VM)) {
return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
}
if (template.contains(CONTROLLER_JAVA_VM)) {
return packagePath + "controller" + File.separator + className + "Controller.java";
}
if (template.contains(MAPPER_XML_VM)) {
return resourcePath + "mapper" + File.separator + className + "Mapper.xml";
}
if (template.contains(API_JS_VM)) {
return apiPath + className.toLowerCase() + ".js";
}
return null;
}
} | repos\spring-boot-demo-master\demo-codegen\src\main\java\com\xkcoding\codegen\utils\CodeGenUtil.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
} | repos\Activiti-develop\activiti-core-common\activiti-project-model\src\main\java\org\activiti\core\common\project\model\ProjectManifest.java | 1 |
请完成以下Java代码 | public class HttpFileToMultipartFileUtil {
/**
* 获取
*
* @param fileUrl
* @param filename
* @return
* @throws Exception
*/
public static MultipartFile httpFileToMultipartFile(String fileUrl, String filename) throws Exception {
byte[] bytes = downloadImageData(fileUrl);
return convertByteToMultipartFile(bytes, filename);
}
/**
* 下载图片数据
*/
private static byte[] downloadImageData(String fileUrl) throws IOException {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
connection.setRequestProperty("Accept", "image/*");
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP请求失败,响应码: " + responseCode);
}
try (InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
return outputStream.toByteArray();
} finally { | connection.disconnect();
}
}
/**
* byte转 MultipartFile
*
* @param data
* @param fileName
* @return
*/
private static MultipartFile convertByteToMultipartFile(byte[] data, String fileName) {
FileItemFactory factory = new DiskFileItemFactory();
FileItem item = factory.createItem(fileName, "application/octet-stream", true, fileName);
try (OutputStream os = item.getOutputStream();
ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new RuntimeException("字节数组转换失败", e);
}
try {
return new MyCommonsMultipartFile(item);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\util\HttpFileToMultipartFileUtil.java | 1 |
请完成以下Java代码 | protected String encode(String data) {
return encode(data.getBytes(StandardCharsets.UTF_8));
}
protected String encode(byte[] data) {
if (data == null || data.length == 0) {
return "";
}
return Base64.getEncoder().encodeToString(data);
}
protected String decode(String value) {
if (value == null) {
return null;
}
return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8);
}
private final PaginatedRemover<TenantId, TbResourceId> tenantResourcesRemover = new PaginatedRemover<>() {
@Override
protected PageData<TbResourceId> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return resourceDao.findIdsByTenantId(id.getId(), pageLink); | }
@Override
protected void removeEntity(TenantId tenantId, TbResourceId resourceId) {
deleteResource(tenantId, resourceId, true);
}
};
@TransactionalEventListener(classes = ResourceInfoEvictEvent.class)
@Override
public void handleEvictEvent(ResourceInfoEvictEvent event) {
if (event.getResourceId() != null) {
cache.evict(new ResourceInfoCacheKey(event.getResourceId()));
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\resource\BaseResourceService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String dataSource = element.getAttribute(ATT_DATA_SOURCE);
if (StringUtils.hasText(dataSource)) {
builder.addPropertyReference("dataSource", dataSource);
}
else {
parserContext.getReaderContext()
.error(ATT_DATA_SOURCE + " is required for " + Elements.JDBC_USER_SERVICE,
parserContext.extractSource(element));
}
String usersQuery = element.getAttribute(ATT_USERS_BY_USERNAME_QUERY);
String authoritiesQuery = element.getAttribute(ATT_AUTHORITIES_BY_USERNAME_QUERY);
String groupAuthoritiesQuery = element.getAttribute(ATT_GROUP_AUTHORITIES_QUERY);
String rolePrefix = element.getAttribute(ATT_ROLE_PREFIX);
if (StringUtils.hasText(rolePrefix)) { | builder.addPropertyValue("rolePrefix", rolePrefix);
}
if (StringUtils.hasText(usersQuery)) {
builder.addPropertyValue("usersByUsernameQuery", usersQuery);
}
if (StringUtils.hasText(authoritiesQuery)) {
builder.addPropertyValue("authoritiesByUsernameQuery", authoritiesQuery);
}
if (StringUtils.hasText(groupAuthoritiesQuery)) {
builder.addPropertyValue("enableGroups", Boolean.TRUE);
builder.addPropertyValue("groupAuthoritiesByUsernameQuery", groupAuthoritiesQuery);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\authentication\JdbcUserServiceBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public Optional<I_M_InOutLine> getReversalLineForLineId(@NonNull final InOutLineId inoutLineId)
{
final I_M_InOutLine inOutLine = load(inoutLineId, I_M_InOutLine.class);
if (inOutLine == null)
{
return Optional.empty();
}
if (inOutLine.getReversalLine_ID() <= 0)
{
return Optional.empty();
}
return Optional.ofNullable(load(inOutLine.getReversalLine_ID(), I_M_InOutLine.class));
}
@Override
public ImmutableList<InOutId> retrieveShipmentsWithoutShipperTransportation(@NonNull final Timestamp date)
{
return queryBL
.createQueryBuilder(de.metas.inout.model.I_M_InOut.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut.COLUMNNAME_MovementDate, date)
.addEqualsFilter(I_M_InOut.COLUMNNAME_IsSOTrx, true)
.addEqualsFilter(de.metas.inout.model.I_M_InOut.COLUMNNAME_M_ShipperTransportation, null)
.create()
.idsAsSet(InOutId::ofRepoId)
.asList();
}
@Override
public Stream<I_M_InOut> retrieveByQuery(@NonNull final InOutQuery query)
{
return toSqlQuery(query).create().stream();
}
private IQueryBuilder<I_M_InOut> toSqlQuery(@NonNull final InOutQuery query)
{ | final IQueryBuilder<I_M_InOut> sqlQueryBuilder = queryBL.createQueryBuilder(I_M_InOut.class)
.setLimit(query.getLimit())
.addOnlyActiveRecordsFilter();
if (query.getMovementDateFrom() != null)
{
sqlQueryBuilder.addCompareFilter(I_M_InOut.COLUMNNAME_MovementDate, Operator.GREATER_OR_EQUAL, query.getMovementDateFrom());
}
if (query.getMovementDateTo() != null)
{
sqlQueryBuilder.addCompareFilter(I_M_InOut.COLUMNNAME_MovementDate, Operator.LESS_OR_EQUAL, query.getMovementDateTo());
}
if (query.getDocStatus() != null)
{
sqlQueryBuilder.addEqualsFilter(I_M_InOut.COLUMNNAME_DocStatus, query.getDocStatus());
}
if (query.getExcludeDocStatuses() != null && !query.getExcludeDocStatuses().isEmpty())
{
sqlQueryBuilder.addNotInArrayFilter(I_M_InOut.COLUMNNAME_DocStatus, query.getExcludeDocStatuses());
}
if (!query.getOrderIds().isEmpty())
{
sqlQueryBuilder.addInArrayFilter(I_M_InOut.COLUMNNAME_C_Order_ID, query.getOrderIds());
}
return sqlQueryBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\impl\InOutDAO.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() { | return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getHidden() {
return hidden;
}
public void setHidden(Integer hidden) {
this.hidden = hidden;
}
@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(", parentId=").append(parentId);
sb.append(", createTime=").append(createTime);
sb.append(", title=").append(title);
sb.append(", level=").append(level);
sb.append(", sort=").append(sort);
sb.append(", name=").append(name);
sb.append(", icon=").append(icon);
sb.append(", hidden=").append(hidden);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMenu.java | 1 |
请完成以下Java代码 | public static final class Builder {
private @Nullable AuthenticationEntryPoint defaultEntryPoint;
private List<RequestMatcherEntry<AuthenticationEntryPoint>> entryPoints = new ArrayList<RequestMatcherEntry<AuthenticationEntryPoint>>();
/**
* Set the default {@link AuthenticationEntryPoint} if none match. The default is
* to use the first {@link AuthenticationEntryPoint} added in
* {@link #addEntryPointFor(AuthenticationEntryPoint, RequestMatcher)}.
* @param defaultEntryPoint the default {@link AuthenticationEntryPoint} to use.
* @return the {@link Builder} for further customization.
*/
public Builder defaultEntryPoint(@Nullable AuthenticationEntryPoint defaultEntryPoint) {
this.defaultEntryPoint = defaultEntryPoint;
return this;
}
/**
* Adds an {@link AuthenticationEntryPoint} for the provided
* {@link RequestMatcher}.
* @param entryPoint the {@link AuthenticationEntryPoint} to use. Cannot be null.
* @param requestMatcher the {@link RequestMatcher} to use. Cannot be null.
* @return the {@link Builder} for further customization.
*/
public Builder addEntryPointFor(AuthenticationEntryPoint entryPoint, RequestMatcher requestMatcher) {
Assert.notNull(entryPoint, "entryPoint cannot be null");
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.entryPoints.add(new RequestMatcherEntry<>(requestMatcher, entryPoint));
return this;
}
/**
* Builds the {@link AuthenticationEntryPoint}. If the
* {@link #defaultEntryPoint(AuthenticationEntryPoint)} is not set, then the first
* {@link #addEntryPointFor(AuthenticationEntryPoint, RequestMatcher)} is used as
* the default. If the {@link #defaultEntryPoint(AuthenticationEntryPoint)} is not
* set and there is only a single
* {@link #addEntryPointFor(AuthenticationEntryPoint, RequestMatcher)}, then the | * {@link AuthenticationEntryPoint} is returned rather than wrapping it in
* {@link DelegatingAuthenticationEntryPoint}.
* @return the {@link AuthenticationEntryPoint} to use.
*/
public AuthenticationEntryPoint build() {
AuthenticationEntryPoint defaultEntryPoint = this.defaultEntryPoint;
if (defaultEntryPoint == null) {
Assert.state(!this.entryPoints.isEmpty(), "entryPoints cannot be empty if defaultEntryPoint is null");
AuthenticationEntryPoint firstAuthenticationEntryPoint = this.entryPoints.get(0).getEntry();
if (this.entryPoints.size() == 1) {
return firstAuthenticationEntryPoint;
}
defaultEntryPoint = firstAuthenticationEntryPoint;
}
else if (this.entryPoints.isEmpty()) {
return defaultEntryPoint;
}
return new DelegatingAuthenticationEntryPoint(defaultEntryPoint, this.entryPoints);
}
private Builder() {
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonResponseBPRelationItem
{
@JsonProperty
Integer bpartnerId;
@JsonProperty
@Nullable
Integer locationId;
@JsonProperty
Integer targetBPartnerId;
@JsonProperty
Integer targetBPLocationId;
@JsonProperty
String name;
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_NULL)
String description;
@JsonProperty
JsonExternalId externalId;
@JsonProperty
JsonBPRelationRole role;
@JsonProperty
boolean billTo;
@JsonProperty
boolean fetchedFrom;
@JsonProperty
boolean handoverLocation;
@JsonProperty
boolean payFrom;
@JsonProperty
boolean remitTo;
@JsonProperty
boolean shipTo;
@JsonProperty
boolean active; | @Builder(toBuilder = true)
@JsonCreator
private JsonResponseBPRelationItem(
@JsonProperty("bpartnerId") @NonNull final Integer bpartnerId,
@JsonProperty("locationId") @Nullable final Integer locationId,
@JsonProperty("targetBPartnerId") @NonNull final Integer targetBPartnerId,
@JsonProperty("targetBPLocationId") @NonNull final Integer targetBPLocationId,
@JsonProperty("name") @NonNull final String name,
@JsonProperty("description") final String description,
@JsonProperty("externalId") final JsonExternalId externalId,
@JsonProperty("role") final JsonBPRelationRole role,
@JsonProperty("shipTo") final Boolean shipTo,
@JsonProperty("payFrom") final Boolean payFrom,
@JsonProperty("billTo") final Boolean billTo,
@JsonProperty("handoverLocation") final Boolean handoverLocation,
@JsonProperty("fetchedFrom") final Boolean fetchedFrom,
@JsonProperty("remitTo") final Boolean remitTo,
@JsonProperty("active") final boolean active)
{
this.bpartnerId = bpartnerId;
this.locationId = locationId;
this.targetBPartnerId = targetBPartnerId;
this.targetBPLocationId = targetBPLocationId;
this.name = name;
this.description = description;
this.externalId = externalId;
this.role = role;
this.shipTo = shipTo;
this.payFrom = payFrom;
this.billTo = billTo;
this.handoverLocation = handoverLocation;
this.fetchedFrom = fetchedFrom;
this.remitTo = remitTo;
this.active = active;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bprelation\response\JsonResponseBPRelationItem.java | 2 |
请完成以下Java代码 | public void setQtyEnteredInBPartnerUOM(final I_C_InvoiceLine invoiceLine)
{
if (invoiceLine.getC_OrderLine_ID() <= 0)
{
invoiceLine.setC_UOM_BPartner_ID(0);
invoiceLine.setQtyEnteredInBPartnerUOM(null);
return;
}
final I_C_OrderLine orderLine = orderDAO.getOrderLineById(OrderLineId.ofRepoId(invoiceLine.getC_OrderLine_ID()), I_C_OrderLine.class);
if (orderLine.getC_UOM_BPartner_ID() <= 0 || orderLine.getQtyEnteredInBPartnerUOM().signum() == 0)
{
invoiceLine.setC_UOM_BPartner_ID(0);
invoiceLine.setQtyEnteredInBPartnerUOM(null);
return;
}
final Quantity qtyInvoicedInStockUOM = invoiceLineBL.getQtyEnteredInStockUOM(invoiceLine);
//dev-note: calculating invoicedQtyInBPartnerUOM using proportion to avoid missing UOM conversion between
//BPartner_UOM_ID - which might not be considered at all in metas internal processing - and actual stock UOM
final Quantity invoicedQtyInBPartnerUOM = qtyInvoicedInStockUOM | .multiply(orderLine.getQtyEnteredInBPartnerUOM())
.divide(orderLine.getQtyOrdered());
if (invoicedQtyInBPartnerUOM.signum() < 0)
{
invoiceLine.setQtyEnteredInBPartnerUOM(BigDecimal.ZERO);
}
else
{
invoiceLine.setQtyEnteredInBPartnerUOM(invoicedQtyInBPartnerUOM.toBigDecimal());
}
invoiceLine.setC_UOM_BPartner_ID(orderLine.getC_UOM_BPartner_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\C_InvoiceLine.java | 1 |
请完成以下Java代码 | public String index() {
return "external";
}
@GetMapping("/logout")
public String logout(HttpServletRequest request) throws Exception {
request.logout();
return "redirect:/";
}
@GetMapping(path = "/customers")
public String customers(Principal principal, Model model) {
addCustomers();
Iterable<Customer> customers = customerDAO.findAll();
model.addAttribute("customers", customers);
model.addAttribute("username", principal.getName());
return "customers";
}
// add customers for demonstration
public void addCustomers() {
Customer customer1 = new Customer();
customer1.setAddress("1111 foo blvd");
customer1.setName("Foo Industries"); | customer1.setServiceRendered("Important services");
customerDAO.save(customer1);
Customer customer2 = new Customer();
customer2.setAddress("2222 bar street");
customer2.setName("Bar LLP");
customer2.setServiceRendered("Important services");
customerDAO.save(customer2);
Customer customer3 = new Customer();
customer3.setAddress("33 main street");
customer3.setName("Big LLC");
customer3.setServiceRendered("Important services");
customerDAO.save(customer3);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-adapters\src\main\java\com\baeldung\keycloak\WebController.java | 1 |
请完成以下Java代码 | public String getDefaultDescription() {
return defaultDescription;
}
public void setDefaultDescription(String defaultDescription) {
this.defaultDescription = defaultDescription;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
@Override
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("[Validation set: '").append(validatorSetName).append("' | Problem: '").append(problem).append("'] : ");
strb.append(defaultDescription);
strb.append(" - [Extra info : ");
boolean extraInfoAlreadyPresent = false;
if (caseDefinitionId != null) {
strb.append("caseDefinitionId = ").append(caseDefinitionId);
extraInfoAlreadyPresent = true;
} | if (caseDefinitionName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("caseDefinitionName = ").append(caseDefinitionName).append(" | ");
extraInfoAlreadyPresent = true;
}
if (itemId != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("id = ").append(itemId).append(" | ");
extraInfoAlreadyPresent = true;
}
if (itemName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("name = ").append(itemName).append(" | ");
extraInfoAlreadyPresent = true;
}
strb.append("]");
if (xmlLineNumber > 0 && xmlColumnNumber > 0) {
strb.append(" ( line: ").append(xmlLineNumber).append(", column: ").append(xmlColumnNumber).append(")");
}
return strb.toString();
}
} | repos\flowable-engine-main\modules\flowable-case-validation\src\main\java\org\flowable\cmmn\validation\validator\ValidationEntry.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public UserName getUserName() {
return userName;
}
public Email getEmail() {
return email;
}
public void setUserName(@Nullable UserName userName) {
this.userName = userName;
}
public void setEmail(@Nullable Email email) {
this.email = email;
} | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
var user = (User) o;
return Objects.equals(id, user.id) &&
Objects.equals(userName, user.userName) &&
Objects.equals(email, user.email);
}
@Override
public int hashCode() {
return Objects.hash(id, userName, email);
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", userName=" + userName +
", email=" + email +
'}';
}
} | repos\spring-data-examples-main\mongodb\example\src\main\java\example\springdata\mongodb\unwrapping\User.java | 1 |
请完成以下Java代码 | private static class ArtifactIdCapability extends TextCapability {
private final TextCapability nameCapability;
ArtifactIdCapability(TextCapability nameCapability) {
super("artifactId", "Artifact", "project coordinates (infer archive name)");
this.nameCapability = nameCapability;
}
@Override
public String getContent() {
String value = super.getContent();
return (value != null) ? value : this.nameCapability.getContent();
}
}
private static class PackageCapability extends TextCapability {
private final TextCapability groupId;
private final TextCapability artifactId;
PackageCapability(TextCapability groupId, TextCapability artifactId) {
super("packageName", "Package Name", "root package");
this.groupId = groupId;
this.artifactId = artifactId;
} | @Override
public String getContent() {
String value = super.getContent();
if (value != null) {
return value;
}
else if (this.groupId.getContent() != null && this.artifactId.getContent() != null) {
return InitializrConfiguration
.cleanPackageName(this.groupId.getContent() + "." + this.artifactId.getContent());
}
return null;
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrMetadata.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class NewRelicPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<NewRelicProperties>
implements NewRelicConfig {
public NewRelicPropertiesConfigAdapter(NewRelicProperties properties) {
super(properties);
}
@Override
public String prefix() {
return "management.newrelic.metrics.export";
}
@Override
public boolean meterNameEventTypeEnabled() {
return obtain(NewRelicProperties::isMeterNameEventTypeEnabled, NewRelicConfig.super::meterNameEventTypeEnabled);
}
@Override
public String eventType() {
return obtain(NewRelicProperties::getEventType, NewRelicConfig.super::eventType);
}
@Override
public ClientProviderType clientProviderType() {
return obtain(NewRelicProperties::getClientProviderType, NewRelicConfig.super::clientProviderType);
} | @Override
public @Nullable String apiKey() {
return get(NewRelicProperties::getApiKey, NewRelicConfig.super::apiKey);
}
@Override
public @Nullable String accountId() {
return get(NewRelicProperties::getAccountId, NewRelicConfig.super::accountId);
}
@Override
public String uri() {
return obtain(NewRelicProperties::getUri, NewRelicConfig.super::uri);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\newrelic\NewRelicPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public static final class Builder
{
private Integer adMenuId;
private String caption;
private String captionBreadcrumb;
private MenuNodeType type;
@Nullable private DocumentId elementId;
private String mainTableName;
private final List<MenuNode> childrenFirst = new ArrayList<>();
private final List<MenuNode> childrenRest = new ArrayList<>();
private Builder()
{
}
public MenuNode build()
{
return new MenuNode(this);
}
public Builder setAD_Menu_ID(final int adMenuId)
{
this.adMenuId = adMenuId;
return this;
}
public Builder setAD_Menu_ID_None()
{
// NOTE: don't set it to ZERO because ZERO is usually root node's ID.
this.adMenuId = -100;
return this;
}
private int getAD_Menu_ID()
{
Check.assumeNotNull(adMenuId, "adMenuId shall be set");
return adMenuId;
}
private String getId()
{
final int adMenuId = getAD_Menu_ID();
if (type == MenuNodeType.NewRecord)
{
return adMenuId + "-new";
}
else
{
return String.valueOf(adMenuId);
}
}
public Builder setCaption(final String caption)
{
this.caption = caption;
return this;
}
public Builder setCaptionBreadcrumb(final String captionBreadcrumb)
{
this.captionBreadcrumb = captionBreadcrumb;
return this;
}
public Builder setType(final MenuNodeType type, @Nullable final DocumentId elementId) | {
this.type = type;
this.elementId = elementId;
return this;
}
public Builder setTypeNewRecord(@NonNull final AdWindowId adWindowId)
{
return setType(MenuNodeType.NewRecord, DocumentId.of(adWindowId));
}
public void setTypeGroup()
{
setType(MenuNodeType.Group, null);
}
public void addChildToFirstsList(@NonNull final MenuNode child)
{
childrenFirst.add(child);
}
public void addChild(@NonNull final MenuNode child)
{
childrenRest.add(child);
}
public Builder setMainTableName(final String mainTableName)
{
this.mainTableName = mainTableName;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuNode.java | 1 |
请完成以下Java代码 | public final class StrictTransportSecurityServerHttpHeadersWriter implements ServerHttpHeadersWriter {
public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security";
private String maxAge;
private String subdomain;
private String preload;
private ServerHttpHeadersWriter delegate;
public StrictTransportSecurityServerHttpHeadersWriter() {
setIncludeSubDomains(true);
setMaxAge(Duration.ofDays(365L));
setPreload(false);
updateDelegate();
}
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return isSecure(exchange) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty();
}
/**
* Sets if subdomains should be included. Default is true
* @param includeSubDomains if subdomains should be included
*/
public void setIncludeSubDomains(boolean includeSubDomains) {
this.subdomain = includeSubDomains ? " ; includeSubDomains" : "";
updateDelegate();
}
/**
* <p>
* Sets if preload should be included. Default is false
* </p>
*
* <p>
* See <a href="https://hstspreload.org/">Website hstspreload.org</a> for additional
* details.
* </p> | * @param preload if preload should be included
* @since 5.2.0
*/
public void setPreload(boolean preload) {
this.preload = preload ? " ; preload" : "";
updateDelegate();
}
/**
* Sets the max age of the header. Default is a year.
* @param maxAge the max age of the header
*/
public void setMaxAge(Duration maxAge) {
this.maxAge = "max-age=" + maxAge.getSeconds();
updateDelegate();
}
private void updateDelegate() {
Builder builder = StaticServerHttpHeadersWriter.builder();
builder.header(STRICT_TRANSPORT_SECURITY, this.maxAge + this.subdomain + this.preload);
this.delegate = builder.build();
}
private boolean isSecure(ServerWebExchange exchange) {
String scheme = exchange.getRequest().getURI().getScheme();
boolean isSecure = scheme != null && scheme.equalsIgnoreCase("https");
return isSecure;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\StrictTransportSecurityServerHttpHeadersWriter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BroadcastMessageApp {
private static String ROUTING_KEY_USER_IMPORTANT_WARN = "user.important.warn";
private static String ROUTING_KEY_USER_IMPORTANT_ERROR = "user.important.error";
public static void main(String[] args) {
SpringApplication.run(BroadcastMessageApp.class, args);
}
@Bean
public ApplicationRunner runner(RabbitTemplate rabbitTemplate) {
String message = " payload is broadcast";
return args -> {
rabbitTemplate.convertAndSend(BroadcastConfig.FANOUT_EXCHANGE_NAME, "", "fanout" + message);
rabbitTemplate.convertAndSend(BroadcastConfig.TOPIC_EXCHANGE_NAME, ROUTING_KEY_USER_IMPORTANT_WARN, "topic important warn" + message);
rabbitTemplate.convertAndSend(BroadcastConfig.TOPIC_EXCHANGE_NAME, ROUTING_KEY_USER_IMPORTANT_ERROR, "topic important error" + message);
};
}
@RabbitListener(queues = { FANOUT_QUEUE_1_NAME })
public void receiveMessageFromFanout1(String message) { | System.out.println("Received fanout 1 message: " + message);
}
@RabbitListener(queues = { FANOUT_QUEUE_2_NAME })
public void receiveMessageFromFanout2(String message) {
System.out.println("Received fanout 2 message: " + message);
}
@RabbitListener(queues = { TOPIC_QUEUE_1_NAME })
public void receiveMessageFromTopic1(String message) {
System.out.println("Received topic 1 (" + BINDING_PATTERN_IMPORTANT + ") message: " + message);
}
@RabbitListener(queues = { TOPIC_QUEUE_2_NAME })
public void receiveMessageFromTopic2(String message) {
System.out.println("Received topic 2 (" + BINDING_PATTERN_ERROR + ") message: " + message);
}
} | repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\broadcast\BroadcastMessageApp.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Attribute
{
@NonNull AttributeCode attributeCode;
@NonNull ITranslatableString displayName;
@NonNull AttributeValueType valueType;
@Nullable Object value;
public static Attribute of(@NonNull final org.adempiere.mm.attributes.api.Attribute attributeDescriptor)
{
return Attribute.builder()
.attributeCode(attributeDescriptor.getAttributeCode())
.displayName(attributeDescriptor.getDisplayName())
.valueType(attributeDescriptor.getValueType())
.value(null)
.build();
}
public String getValueAsString()
{
return value != null ? value.toString() : null;
}
public BigDecimal getValueAsBigDecimal()
{
return value != null ? NumberUtils.asBigDecimal(value) : null;
}
public LocalDate getValueAsLocalDate()
{
return value == null ? null : TimeUtil.asLocalDate(value);
}
public Object getValueAsJson()
{
if (AttributeValueType.STRING.equals(valueType))
{
return getValueAsString();
}
else if (AttributeValueType.NUMBER.equals(valueType))
{
return getValueAsBigDecimal();
}
else if (AttributeValueType.DATE.equals(valueType))
{
final LocalDate value = getValueAsLocalDate();
return value != null ? value.toString() : null;
}
else if (AttributeValueType.LIST.equals(valueType))
{
return getValueAsString();
}
else | {
throw new AdempiereException("Unknown attribute type: " + valueType);
}
}
public ITranslatableString getValueAsTranslatableString()
{
switch (valueType)
{
case STRING:
case LIST:
{
final String valueStr = getValueAsString();
return TranslatableStrings.anyLanguage(valueStr);
}
case NUMBER:
{
final BigDecimal valueBD = getValueAsBigDecimal();
return valueBD != null
? TranslatableStrings.number(valueBD, de.metas.common.util.NumberUtils.isInteger(valueBD) ? DisplayType.Integer : DisplayType.Number)
: TranslatableStrings.empty();
}
case DATE:
{
final LocalDate valueDate = getValueAsLocalDate();
return valueDate != null
? TranslatableStrings.date(valueDate, DisplayType.Date)
: TranslatableStrings.empty();
}
default:
{
return TranslatableStrings.empty();
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\Attribute.java | 2 |
请完成以下Java代码 | public java.lang.String getModelPackage ()
{
return (java.lang.String)get_Value(COLUMNNAME_ModelPackage);
}
/** 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 Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); | return "Y".equals(oo);
}
return false;
}
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.lang.String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.lang.String getVersion ()
{
return (java.lang.String)get_Value(COLUMNNAME_Version);
}
/** Set WebUIServletListener Class.
@param WebUIServletListenerClass
Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener
*/
@Override
public void setWebUIServletListenerClass (java.lang.String WebUIServletListenerClass)
{
set_Value (COLUMNNAME_WebUIServletListenerClass, WebUIServletListenerClass);
}
/** Get WebUIServletListener Class.
@return Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener
*/
@Override
public java.lang.String getWebUIServletListenerClass ()
{
return (java.lang.String)get_Value(COLUMNNAME_WebUIServletListenerClass);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_EntityType.java | 1 |
请完成以下Java代码 | public void write(byte[] b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkContentLength(len);
this.delegate.write(b, off, len);
}
@Override
public boolean isReady() {
return this.delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
this.delegate.setWriteListener(writeListener);
}
@Override | public boolean equals(Object obj) {
return this.delegate.equals(obj);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]";
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\OnCommittedResponseWrapper.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public List<String> getImageUrls() {
return imageUrls;
} | public void setImageUrls(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
public List<String> getVideoUrls() {
return videoUrls;
}
public void setVideoUrls(List<String> videoUrls) {
this.videoUrls = videoUrls;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public Float getAverageRating() {
return averageRating;
}
public void setAverageRating(Float averageRating) {
this.averageRating = averageRating;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\entity\Product.java | 1 |
请完成以下Java代码 | protected HistoricPlanItemInstanceEntityManager getHistoricPlanItemInstanceEntityManager() {
return cmmnEngineConfiguration.getHistoricPlanItemInstanceEntityManager();
}
protected VariableInstanceEntityManager getVariableInstanceEntityManager() {
return cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableInstanceEntityManager();
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return cmmnEngineConfiguration.getVariableServiceConfiguration().getHistoricVariableInstanceEntityManager();
}
protected IdentityLinkEntityManager getIdentityLinkEntityManager() {
return cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkEntityManager();
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getHistoricIdentityLinkEntityManager();
}
protected EntityLinkEntityManager getEntityLinkEntityManager() {
return cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getEntityLinkEntityManager();
} | protected HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() {
return cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getHistoricEntityLinkEntityManager();
}
protected TaskEntityManager getTaskEntityManager() {
return cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskEntityManager();
}
protected HistoricTaskLogEntryEntityManager getHistoricTaskLogEntryEntityManager() {
return cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskLogEntryEntityManager();
}
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskInstanceEntityManager();
}
protected CmmnEngineConfiguration getCmmnEngineConfiguration() {
return cmmnEngineConfiguration;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\AbstractCmmnManager.java | 1 |
请完成以下Java代码 | public void setExternalSystem_Config_Alberta_ID (final int ExternalSystem_Config_Alberta_ID)
{
if (ExternalSystem_Config_Alberta_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, ExternalSystem_Config_Alberta_ID);
}
@Override
public int getExternalSystem_Config_Alberta_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Alberta_ID);
}
@Override
public I_ExternalSystem_Config getExternalSystem_Config()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class);
}
@Override
public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config);
}
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setExternalSystemValue (final String ExternalSystemValue)
{
set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue);
}
@Override
public String getExternalSystemValue()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemValue);
}
@Override | public void setPharmacy_PriceList_ID (final int Pharmacy_PriceList_ID)
{
if (Pharmacy_PriceList_ID < 1)
set_Value (COLUMNNAME_Pharmacy_PriceList_ID, null);
else
set_Value (COLUMNNAME_Pharmacy_PriceList_ID, Pharmacy_PriceList_ID);
}
@Override
public int getPharmacy_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_Pharmacy_PriceList_ID);
}
@Override
public void setTenant (final String Tenant)
{
set_Value (COLUMNNAME_Tenant, Tenant);
}
@Override
public String getTenant()
{
return get_ValueAsString(COLUMNNAME_Tenant);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Alberta.java | 1 |
请完成以下Java代码 | public void e(CoNLLSentence right, CoNLLSentence test)
{
++sentenceCount;
A += right.word.length;
for (int i = 0; i < test.word.length; ++i)
{
if (test.word[i].HEAD.ID == right.word[i].HEAD.ID)
{
++U;
if (right.word[i].DEPREL.equals(test.word[i].DEPREL))
{
++L;
if (test.word[i].HEAD.ID != 0)
{
++D;
}
}
}
}
}
public float getUA()
{
return U / A;
}
public float getLA()
{
return L / A;
}
public float getDA()
{
return D / (A - sentenceCount); | }
@Override
public String toString()
{
NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setMinimumFractionDigits(2);
StringBuilder sb = new StringBuilder();
sb.append("UA: ");
sb.append(percentFormat.format(getUA()));
sb.append('\t');
sb.append("LA: ");
sb.append(percentFormat.format(getLA()));
sb.append('\t');
sb.append("DA: ");
sb.append(percentFormat.format(getDA()));
sb.append('\t');
sb.append("sentences: ");
sb.append(sentenceCount);
sb.append('\t');
sb.append("speed: ");
sb.append(sentenceCount / (float)(System.currentTimeMillis() - start) * 1000);
sb.append(" sent/s");
return sb.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\CoNll\Evaluator.java | 1 |
请完成以下Java代码 | public class WEBUI_PickingSlotsClearingView_TakeOutHU extends PickingSlotsClearingViewBasedProcess implements IProcessPrecondition
{
private final transient IHUPickingSlotBL huPickingSlotBL = Services.get(IHUPickingSlotBL.class);
private final PickingCandidateService pickingCandidateService = SpringContextHolder.instance.getBean(PickingCandidateService.class);
private final List<HUExtractedFromPickingSlotEvent> husExtractedEvents = new ArrayList<>();
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!selectedRowIds.isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final PickingSlotRow row = getSingleSelectedPickingSlotRow();
if (!row.isTopLevelHU())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select a top level HU");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
//
// Get the HU
final PickingSlotRow huRow = getSingleSelectedPickingSlotRow();
Check.assume(huRow.isTopLevelHU(), "row {} shall be a top level HU", huRow);
final I_M_HU hu = InterfaceWrapperHelper.load(huRow.getHuId(), I_M_HU.class);
//
// Remove the HU from it's picking slot
huPickingSlotBL.removeFromPickingSlotQueueRecursivelly(hu);
//
// Make sure the HU has the BPartner/Location of the picking slot
final PickingSlotRow pickingSlotRow = getRootRowForSelectedPickingSlotRows();
if (pickingSlotRow.getBPartnerId() > 0)
{
hu.setC_BPartner_ID(pickingSlotRow.getBPartnerId());
hu.setC_BPartner_Location_ID(pickingSlotRow.getBPartnerLocationId());
InterfaceWrapperHelper.save(hu);
} | //
// Move the HU to an after picking locator
moveToAfterPickingLocator(hu);
//
// Inactive all those picking candidates
pickingCandidateService.inactivateForHUId(HuId.ofRepoId(hu.getM_HU_ID()));
husExtractedEvents.add(HUExtractedFromPickingSlotEvent.builder()
.huId(hu.getM_HU_ID())
.bpartnerId(hu.getC_BPartner_ID())
.bpartnerLocationId(hu.getC_BPartner_Location_ID())
.build());
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
//
// Invalidate the views
// Expectation: the HU shall disappear from picking slots view (left side) and shall appear on after picking HUs view (right side).
final PickingSlotsClearingView pickingSlotsClearingView = getPickingSlotsClearingView();
invalidateView(pickingSlotsClearingView.getViewId());
//
husExtractedEvents.forEach(pickingSlotsClearingView::handleEvent);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutHU.java | 1 |
请完成以下Java代码 | public class InternationalShipmentRequestedEvent extends ShipmentRequestedEvent {
private String destinationCountry;
private String customsInfo;
public InternationalShipmentRequestedEvent(){}
public InternationalShipmentRequestedEvent(UUID orderId, String customerAddress, LocalDate shipBy, String destinationCountry,
String customsInfo) {
super(orderId, customerAddress, shipBy);
this.destinationCountry = destinationCountry;
this.customsInfo = customsInfo;
}
public InternationalShipment toDomain() {
return new InternationalShipment(getOrderId(), getCustomerAddress(), getShipBy(), ShipmentStatus.REQUESTED, destinationCountry,
customsInfo);
} | public String getDestinationCountry() {
return destinationCountry;
}
public void setDestinationCountry(String destinationCountry) {
this.destinationCountry = destinationCountry;
}
public String getCustomsInfo() {
return customsInfo;
}
public void setCustomsInfo(String customsInfo) {
this.customsInfo = customsInfo;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\conversion\model\event\InternationalShipmentRequestedEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
private String id;
@Column(name = "name", columnDefinition="VARCHAR(128)")
private String name;
@Lob
@Column(name = "photo", columnDefinition="BLOB")
private byte[] photo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id; | }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\lob\model\User.java | 2 |
请完成以下Java代码 | public class EngineClosedEventHandler extends AbstractDatabaseEventLoggerEventHandler {
@Override
public EventLogEntryEntity generateEventLogEntry(CommandContext commandContext) {
Map<String, Object> data = new HashMap<String, Object>();
try {
data.put("ip", InetAddress.getLocalHost().getHostAddress()); // Note
// that
// this
// might
// give
// the
// wrong
// ip
// address
// in | // case
// of
// multiple
// network
// interfaces
// -
// but
// it's
// better
// than
// nothing.
} catch (UnknownHostException e) {
// Best effort
}
return createEventLogEntry(data);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\logger\handler\EngineClosedEventHandler.java | 1 |
请完成以下Java代码 | public Void call() throws Exception {
for (Deployer deployer : deployers) {
deployer.deploy(deployment);
}
return null;
}
});
}
public void deployOnlyGivenResourcesOfDeployment(final DeploymentEntity deployment, String... resourceNames) {
initDeployment(deployment, resourceNames);
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() throws Exception {
for (Deployer deployer : deployers) {
deployer.deploy(deployment);
}
return null;
} | });
deployment.setResources(null);
}
protected void initDeployment(final DeploymentEntity deployment, String... resourceNames) {
deployment.clearResources();
for (String resourceName : resourceNames) {
if (resourceName != null) {
// with the given resource we prevent the deployment of querying
// the database which means using all resources that were utilized during the deployment
ResourceEntity resource = Context.getCommandContext().getResourceManager().findResourceByDeploymentIdAndResourceName(deployment.getId(), resourceName);
deployment.addResource(resource);
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CacheDeployer.java | 1 |
请完成以下Java代码 | public EventDefinition getNoneBehaviorEventRef() {
return noneBehaviorEventRefAttribute.getReferenceTargetElement(this);
}
public void setNoneBehaviorEventRef(EventDefinition noneBehaviorEventRef) {
noneBehaviorEventRefAttribute.setReferenceTargetElement(this, noneBehaviorEventRef);
}
public boolean isCamundaAsyncBefore() {
return camundaAsyncBefore.getValue(this);
}
public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) {
camundaAsyncBefore.setValue(this, isCamundaAsyncBefore);
}
public boolean isCamundaAsyncAfter() {
return camundaAsyncAfter.getValue(this);
}
public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) {
camundaAsyncAfter.setValue(this, isCamundaAsyncAfter);
}
public boolean isCamundaExclusive() {
return camundaExclusive.getValue(this);
} | public void setCamundaExclusive(boolean isCamundaExclusive) {
camundaExclusive.setValue(this, isCamundaExclusive);
}
public String getCamundaCollection() {
return camundaCollection.getValue(this);
}
public void setCamundaCollection(String expression) {
camundaCollection.setValue(this, expression);
}
public String getCamundaElementVariable() {
return camundaElementVariable.getValue(this);
}
public void setCamundaElementVariable(String variableName) {
camundaElementVariable.setValue(this, variableName);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MultiInstanceLoopCharacteristicsImpl.java | 1 |
请完成以下Java代码 | public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
} | public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DeadLetterJobQueryImpl.java | 1 |
请完成以下Java代码 | public void setTemplated(boolean templated) {
this.templated = templated;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHref() {
return this.href;
}
public Set<String> getTemplateVariables() {
return Collections.unmodifiableSet(this.templateVariables);
}
public void setHref(String href) {
this.href = href;
}
public void resolve() {
if (this.rel == null) {
throw new InvalidInitializrMetadataException("Invalid link " + this + ": rel attribute is mandatory");
}
if (this.href == null) {
throw new InvalidInitializrMetadataException("Invalid link " + this + ": href attribute is mandatory");
}
Matcher matcher = VARIABLE_REGEX.matcher(this.href);
while (matcher.find()) {
String variable = matcher.group(1);
this.templateVariables.add(variable);
}
this.templated = !this.templateVariables.isEmpty();
}
/**
* Expand the link using the specified parameters. | * @param parameters the parameters value
* @return an URI where all variables have been expanded
*/
public URI expand(Map<String, String> parameters) {
AtomicReference<String> result = new AtomicReference<>(this.href);
this.templateVariables.forEach((var) -> {
Object value = parameters.get(var);
if (value == null) {
throw new IllegalArgumentException(
"Could not expand " + this.href + ", missing value for '" + var + "'");
}
result.set(result.get().replace("{" + var + "}", value.toString()));
});
try {
return new URI(result.get());
}
catch (URISyntaxException ex) {
throw new IllegalStateException("Invalid URL", ex);
}
}
public static Link create(String rel, String href) {
return new Link(rel, href);
}
public static Link create(String rel, String href, String description) {
return new Link(rel, href, description);
}
public static Link create(String rel, String href, boolean templated) {
return new Link(rel, href, templated);
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Link.java | 1 |
请完成以下Java代码 | public class CompositeMigrationStepExecutor extends AbstractMigrationStepExecutor
{
public CompositeMigrationStepExecutor(final IMigrationExecutorContext migrationCtx, final I_AD_MigrationStep step)
{
super(migrationCtx, step);
}
@Override
public ExecutionResult apply(final String trxName)
{
final I_AD_MigrationStep step = getAD_MigrationStep();
// Already applied
if (X_AD_MigrationStep.STATUSCODE_Applied.equals(step.getStatusCode()))
{
log("Already applied", "SKIP", false);
return ExecutionResult.Ignored;
}
final IMigrationStepExecutor executor = createDelegatedMigrationStepExecutor(step);
return executor.apply(trxName);
}
@Override
public ExecutionResult rollback(final String trxName)
{
final I_AD_MigrationStep step = getAD_MigrationStep();
// Not Applied, no rollback is needed
if (!X_AD_MigrationStep.STATUSCODE_Applied.equals(step.getStatusCode()))
{
log("Not applied. Nothing to rollback", "SKIP", false);
return ExecutionResult.Ignored; | }
final IMigrationStepExecutor executor = createDelegatedMigrationStepExecutor(step);
return executor.rollback(trxName);
}
private IMigrationStepExecutor createDelegatedMigrationStepExecutor(final I_AD_MigrationStep step)
{
final IMigrationExecutorContext migrationCtx = getMigrationExecutorContext();
final IMigrationExecutorProvider factory = migrationCtx.getMigrationExecutorProvider();
final IMigrationStepExecutor executor = factory.newMigrationStepExecutor(migrationCtx, step);
return executor;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\CompositeMigrationStepExecutor.java | 1 |
请完成以下Java代码 | public int getNotificationCount()
{
return delegate().getNotificationCount();
}
@Override
public List<I_AD_Note> getNotifications()
{
return delegate().getNotifications();
}
@Override
public String getNotificationsWhereClause()
{
return delegate().getNotificationsWhereClause();
}
@Override | public void addInvoice(final I_C_Invoice invoice)
{
delegate().addInvoice(invoice);
}
@Override
public void addNotifications(final List<I_AD_Note> notifications)
{
delegate().addNotifications(notifications);
}
@Override
public String getSummary(final Properties ctx)
{
return delegate().getSummary(ctx);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ForwardingInvoiceGenerateResult.java | 1 |
请完成以下Java代码 | public int getAD_Printer_Config_Shared_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Config_Shared_ID);
}
@Override
public void setAD_User_PrinterMatchingConfig_ID (int AD_User_PrinterMatchingConfig_ID)
{
if (AD_User_PrinterMatchingConfig_ID < 1)
set_Value (COLUMNNAME_AD_User_PrinterMatchingConfig_ID, null);
else
set_Value (COLUMNNAME_AD_User_PrinterMatchingConfig_ID, Integer.valueOf(AD_User_PrinterMatchingConfig_ID));
}
@Override
public int getAD_User_PrinterMatchingConfig_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_PrinterMatchingConfig_ID);
}
@Override
public void setConfigHostKey (java.lang.String ConfigHostKey)
{
set_Value (COLUMNNAME_ConfigHostKey, ConfigHostKey);
}
@Override
public java.lang.String getConfigHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_ConfigHostKey);
}
@Override
public void setIsSharedPrinterConfig (boolean IsSharedPrinterConfig)
{
set_Value (COLUMNNAME_IsSharedPrinterConfig, Boolean.valueOf(IsSharedPrinterConfig));
}
@Override
public boolean isSharedPrinterConfig()
{
return get_ValueAsBoolean(COLUMNNAME_IsSharedPrinterConfig);
}
@Override | public org.compiere.model.I_C_Workplace getC_Workplace()
{
return get_ValueAsPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class);
}
@Override
public void setC_Workplace(final org.compiere.model.I_C_Workplace C_Workplace)
{
set_ValueFromPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class, C_Workplace);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Config.java | 1 |
请完成以下Java代码 | public class MigratingScopeInstanceBranch {
protected Map<ScopeImpl, MigratingScopeInstance> scopeInstances;
public MigratingScopeInstanceBranch() {
this(new HashMap<ScopeImpl, MigratingScopeInstance>());
}
protected MigratingScopeInstanceBranch(
Map<ScopeImpl, MigratingScopeInstance> scopeInstances) {
this.scopeInstances = scopeInstances;
}
public MigratingScopeInstanceBranch copy() {
return new MigratingScopeInstanceBranch(
new HashMap<ScopeImpl, MigratingScopeInstance>(scopeInstances));
} | public MigratingScopeInstance getInstance(ScopeImpl scope) {
return scopeInstances.get(scope);
}
public boolean hasInstance(ScopeImpl scope) {
return scopeInstances.containsKey(scope);
}
public void visited(MigratingScopeInstance scopeInstance) {
ScopeImpl targetScope = scopeInstance.getTargetScope();
if (targetScope.isScope()) {
scopeInstances.put(targetScope, scopeInstance);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingScopeInstanceBranch.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey; | }
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java | 2 |
请完成以下Java代码 | public class BpmnEdgeImpl extends LabeledEdgeImpl implements BpmnEdge {
protected static AttributeReference<BaseElement> bpmnElementAttribute;
protected static AttributeReference<DiagramElement> sourceElementAttribute;
protected static AttributeReference<DiagramElement> targetElementAttribute;
protected static Attribute<MessageVisibleKind> messageVisibleKindAttribute;
protected static ChildElement<BpmnLabel> bpmnLabelChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(BpmnEdge.class, BPMNDI_ELEMENT_BPMN_EDGE)
.namespaceUri(BPMNDI_NS)
.extendsType(LabeledEdge.class)
.instanceProvider(new ModelTypeInstanceProvider<BpmnEdge>() {
public BpmnEdge newInstance(ModelTypeInstanceContext instanceContext) {
return new BpmnEdgeImpl(instanceContext);
}
});
bpmnElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_BPMN_ELEMENT)
.qNameAttributeReference(BaseElement.class)
.build();
sourceElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_SOURCE_ELEMENT)
.qNameAttributeReference(DiagramElement.class)
.build();
targetElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_TARGET_ELEMENT)
.qNameAttributeReference(DiagramElement.class)
.build();
messageVisibleKindAttribute = typeBuilder.enumAttribute(BPMNDI_ATTRIBUTE_MESSAGE_VISIBLE_KIND, MessageVisibleKind.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
bpmnLabelChild = sequenceBuilder.element(BpmnLabel.class)
.build();
typeBuilder.build();
}
public BpmnEdgeImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public BaseElement getBpmnElement() {
return bpmnElementAttribute.getReferenceTargetElement(this);
} | public void setBpmnElement(BaseElement bpmnElement) {
bpmnElementAttribute.setReferenceTargetElement(this, bpmnElement);
}
public DiagramElement getSourceElement() {
return sourceElementAttribute.getReferenceTargetElement(this);
}
public void setSourceElement(DiagramElement sourceElement) {
sourceElementAttribute.setReferenceTargetElement(this, sourceElement);
}
public DiagramElement getTargetElement() {
return targetElementAttribute.getReferenceTargetElement(this);
}
public void setTargetElement(DiagramElement targetElement) {
targetElementAttribute.setReferenceTargetElement(this, targetElement);
}
public MessageVisibleKind getMessageVisibleKind() {
return messageVisibleKindAttribute.getValue(this);
}
public void setMessageVisibleKind(MessageVisibleKind messageVisibleKind) {
messageVisibleKindAttribute.setValue(this, messageVisibleKind);
}
public BpmnLabel getBpmnLabel() {
return bpmnLabelChild.getChild(this);
}
public void setBpmnLabel(BpmnLabel bpmnLabel) {
bpmnLabelChild.setChild(this, bpmnLabel);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnEdgeImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static RelationalManagedTypes r2dbcManagedTypes(ApplicationContext applicationContext)
throws ClassNotFoundException {
return RelationalManagedTypes.fromIterable(new EntityScanner(applicationContext).scan(Table.class));
}
@Bean
@ConditionalOnMissingBean
R2dbcMappingContext r2dbcMappingContext(ObjectProvider<NamingStrategy> namingStrategy,
R2dbcCustomConversions r2dbcCustomConversions, RelationalManagedTypes r2dbcManagedTypes) {
R2dbcMappingContext relationalMappingContext = new R2dbcMappingContext(
namingStrategy.getIfAvailable(() -> DefaultNamingStrategy.INSTANCE));
relationalMappingContext.setSimpleTypeHolder(r2dbcCustomConversions.getSimpleTypeHolder());
relationalMappingContext.setManagedTypes(r2dbcManagedTypes);
return relationalMappingContext;
}
@Bean
@ConditionalOnMissingBean | MappingR2dbcConverter r2dbcConverter(R2dbcMappingContext mappingContext,
R2dbcCustomConversions r2dbcCustomConversions) {
return new MappingR2dbcConverter(mappingContext, r2dbcCustomConversions);
}
@Bean
@ConditionalOnMissingBean
R2dbcCustomConversions r2dbcCustomConversions() {
List<Object> converters = new ArrayList<>(this.dialect.getConverters());
converters.addAll(R2dbcCustomConversions.STORE_CONVERTERS);
return new R2dbcCustomConversions(
CustomConversions.StoreConversions.of(this.dialect.getSimpleTypeHolder(), converters),
Collections.emptyList());
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-r2dbc\src\main\java\org\springframework\boot\data\r2dbc\autoconfigure\DataR2dbcAutoConfiguration.java | 2 |
请完成以下Java代码 | 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 Start Date.
@param StartDate | First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionPreCondition.java | 1 |
请完成以下Java代码 | public class GameDTO {
private Long id;
private String name;
private Long creationTime;
private String creatorId;
private String creator;
private int totalPlayers;
private List<PlayerDTO> players;
private GameMode mode;
private int maxPlayers;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Long getCreationTime() {
return this.creationTime;
}
public void setCreationTime(Long creationTime) {
this.creationTime = creationTime;
}
public String getCreatorId() {
return this.creatorId;
}
public void setCreatorId(String creatorId) {
this.creatorId = creatorId;
}
public String getCreator() {
return this.creator;
} | public void setCreator(String creator) {
this.creator = creator;
}
public int getTotalPlayers() {
return this.totalPlayers;
}
public void setTotalPlayers(int totalPlayers) {
this.totalPlayers = totalPlayers;
}
public GameMode getMode() {
return this.mode;
}
public void setMode(GameMode mode) {
this.mode = mode;
}
public int getMaxPlayers() {
return this.maxPlayers;
}
public void setMaxPlayers(int maxPlayers) {
this.maxPlayers = maxPlayers;
}
public List<PlayerDTO> getPlayers() {
return this.players;
}
public void setPlayers(List<PlayerDTO> players) {
this.players = players;
}
} | repos\tutorials-master\libraries-data\src\main\java\com\baeldung\modelmapper\dto\GameDTO.java | 1 |
请完成以下Java代码 | public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
@Override
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);
}
@Override
public void setFeePercentageOfGrandTotal (final BigDecimal FeePercentageOfGrandTotal)
{
set_Value (COLUMNNAME_FeePercentageOfGrandTotal, FeePercentageOfGrandTotal);
}
@Override
public BigDecimal getFeePercentageOfGrandTotal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_FeePercentageOfGrandTotal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setInvoiceProcessingServiceCompany_BPartnerAssignment_ID (final int InvoiceProcessingServiceCompany_BPartnerAssignment_ID)
{
if (InvoiceProcessingServiceCompany_BPartnerAssignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, InvoiceProcessingServiceCompany_BPartnerAssignment_ID);
}
@Override
public int getInvoiceProcessingServiceCompany_BPartnerAssignment_ID()
{
return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID); | }
@Override
public org.compiere.model.I_InvoiceProcessingServiceCompany getInvoiceProcessingServiceCompany()
{
return get_ValueAsPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class);
}
@Override
public void setInvoiceProcessingServiceCompany(final org.compiere.model.I_InvoiceProcessingServiceCompany InvoiceProcessingServiceCompany)
{
set_ValueFromPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class, InvoiceProcessingServiceCompany);
}
@Override
public void setInvoiceProcessingServiceCompany_ID (final int InvoiceProcessingServiceCompany_ID)
{
if (InvoiceProcessingServiceCompany_ID < 1)
set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, null);
else
set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, InvoiceProcessingServiceCompany_ID);
}
@Override
public int getInvoiceProcessingServiceCompany_ID()
{
return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_InvoiceProcessingServiceCompany_BPartnerAssignment.java | 1 |
请完成以下Java代码 | private void setConnectTimeout(ClientHttpRequestFactory factory, Duration connectTimeout) {
Method method = tryFindMethod(factory, "setConnectTimeout", Duration.class);
if (method != null) {
invoke(factory, method, connectTimeout);
return;
}
method = findMethod(factory, "setConnectTimeout", int.class);
int timeout = Math.toIntExact(connectTimeout.toMillis());
invoke(factory, method, timeout);
}
private void setReadTimeout(ClientHttpRequestFactory factory, Duration readTimeout) {
Method method = tryFindMethod(factory, "setReadTimeout", Duration.class);
if (method != null) {
invoke(factory, method, readTimeout);
return;
}
method = findMethod(factory, "setReadTimeout", int.class);
int timeout = Math.toIntExact(readTimeout.toMillis());
invoke(factory, method, timeout);
}
private Method findMethod(ClientHttpRequestFactory requestFactory, String methodName, Class<?>... parameters) {
Method method = ReflectionUtils.findMethod(requestFactory.getClass(), methodName, parameters);
Assert.state(method != null, () -> "Request factory %s does not have a suitable %s method"
.formatted(requestFactory.getClass().getName(), methodName));
Assert.state(!method.isAnnotationPresent(Deprecated.class),
() -> "Request factory %s has the %s method marked as deprecated"
.formatted(requestFactory.getClass().getName(), methodName)); | return method;
}
private @Nullable Method tryFindMethod(ClientHttpRequestFactory requestFactory, String methodName,
Class<?>... parameters) {
Method method = ReflectionUtils.findMethod(requestFactory.getClass(), methodName, parameters);
if (method == null) {
return null;
}
if (method.isAnnotationPresent(Deprecated.class)) {
return null;
}
return method;
}
private void invoke(ClientHttpRequestFactory requestFactory, Method method, Object... parameters) {
ReflectionUtils.invokeMethod(method, requestFactory, parameters);
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\ReflectiveComponentsClientHttpRequestFactoryBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AttributeStorageFactoryService implements IAttributeStorageFactoryService
{
private static final Logger logger = LogManager.getLogger(AttributeStorageFactoryService.class);
private final CopyOnWriteArrayList<Class<? extends IAttributeStorageFactory>> attributeStorageFactories = new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<IAttributeStorageListener> attributeStorageListeners = new CopyOnWriteArrayList<>();
public AttributeStorageFactoryService()
{
// Setup Default Attribute Storage Factories
addAttributeStorageFactory(HUAttributeStorageFactory.class);
addAttributeStorageFactory(ASIAttributeStorageFactory.class);
addAttributeStorageFactory(ASIAwareAttributeStorageFactory.class);
}
@Override
public IAttributeStorageFactory createHUAttributeStorageFactory()
{
final IHUStorageFactory huStorageFactory = Services.get(IHandlingUnitsBL.class).getStorageFactory();
return createHUAttributeStorageFactory(huStorageFactory, HUAttributesDAO.instance);
}
@Override
public IAttributeStorageFactory createHUAttributeStorageFactory(@NonNull final IHUStorageFactory huStorageFactory)
{
return createHUAttributeStorageFactory(huStorageFactory, HUAttributesDAO.instance);
}
@Override
public IAttributeStorageFactory createHUAttributeStorageFactory(
@NonNull final IHUStorageFactory huStorageFactory,
@NonNull final IHUAttributesDAO huAttributesDAO)
{
final IAttributeStorageFactory factory = prepareHUAttributeStorageFactory(huAttributesDAO);
factory.setHUStorageFactory(huStorageFactory);
return factory;
}
@Override
public IAttributeStorageFactory prepareHUAttributeStorageFactory(@NonNull final IHUAttributesDAO huAttributesDAO)
{
final CompositeAttributeStorageFactory factory = new CompositeAttributeStorageFactory();
factory.setHUAttributesDAO(huAttributesDAO);
factory.addAttributeStorageFactoryClasses(attributeStorageFactories);
for (final IAttributeStorageListener attributeStorageListener : attributeStorageListeners)
{
factory.addAttributeStorageListener(attributeStorageListener); | }
return factory;
}
@Override
public void addAttributeStorageFactory(@NonNull final Class<? extends IAttributeStorageFactory> attributeStorageFactoryClass)
{
final boolean added = attributeStorageFactories.addIfAbsent(attributeStorageFactoryClass);
if (added)
{
logger.info("Registered: {}", attributeStorageFactoryClass);
}
else
{
logger.warn("Already registered: {}", attributeStorageFactoryClass);
}
}
@Override
public void addAttributeStorageListener(@NonNull final IAttributeStorageListener attributeStorageListener)
{
attributeStorageListeners.add(attributeStorageListener);
logger.info("Registered: {}", attributeStorageListener);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AttributeStorageFactoryService.java | 2 |
请完成以下Java代码 | public void setIsShowInMainMenu (final boolean IsShowInMainMenu)
{
set_Value (COLUMNNAME_IsShowInMainMenu, IsShowInMainMenu);
}
@Override
public boolean isShowInMainMenu()
{
return get_ValueAsBoolean(COLUMNNAME_IsShowInMainMenu);
}
@Override
public void setMobile_Application_ID (final int Mobile_Application_ID)
{
if (Mobile_Application_ID < 1)
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID);
}
@Override
public int getMobile_Application_ID()
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_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 setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application.java | 1 |
请完成以下Java代码 | public boolean isGreaterThan(@NonNull final Money other) {return compareTo(other) > 0;}
public boolean isEqualByComparingTo(@Nullable final Money other)
{
if (other == null)
{
return false;
}
return other.getCurrencyId().equals(currencyId) && other.toBigDecimal().compareTo(toBigDecimal()) == 0;
}
public static Collector<Money, ?, Stream<Money>> sumByCurrencyAndStream()
{
return sumByCurrencyAnd(map -> map.values().stream());
}
public static Collector<Money, ?, ImmutableMap<CurrencyId, Money>> sumByCurrency()
{
return sumByCurrencyAnd(ImmutableMap::copyOf);
}
public static <T> Collector<Money, ?, T> sumByCurrencyAnd(final Function<Map<CurrencyId, Money>, T> finisher)
{
final Supplier<Map<CurrencyId, Money>> supplier = HashMap::new;
final BiConsumer<Map<CurrencyId, Money>, Money> accumulator = (map, money) -> map.compute(money.getCurrencyId(), (currency, moneyOld) -> moneyOld != null ? moneyOld.add(money) : money);
final BinaryOperator<Map<CurrencyId, Money>> combiner = (l, r) -> {
r.values().forEach(money -> accumulator.accept(l, money));
return l;
};
return Collector.of(supplier, accumulator, combiner, finisher);
}
public Amount toAmount(@NonNull final Function<CurrencyId, CurrencyCode> currencyCodeMapper)
{
return Amount.of(toBigDecimal(), currencyCodeMapper.apply(getCurrencyId()));
}
public Money round(@NonNull final CurrencyPrecision precision)
{
return withValue(precision.round(this.value));
}
public Money roundIfNeeded(@NonNull final CurrencyPrecision precision)
{
return withValue(precision.roundIfNeeded(this.value));
}
public Money round(@NonNull final Function<CurrencyId, CurrencyPrecision> precisionProvider)
{
final CurrencyPrecision precision = precisionProvider.apply(currencyId);
if (precision == null) | {
throw new AdempiereException("No precision was returned by " + precisionProvider + " for " + currencyId);
}
return round(precision);
}
private Money withValue(@NonNull final BigDecimal newValue)
{
return value.compareTo(newValue) != 0 ? of(newValue, currencyId) : this;
}
public static int countNonZero(final Money... array)
{
if (array == null || array.length == 0)
{
return 0;
}
int count = 0;
for (final Money money : array)
{
if (money != null && money.signum() != 0)
{
count++;
}
}
return count;
}
public static boolean equals(@Nullable Money money1, @Nullable Money money2) {return Objects.equals(money1, money2);}
public Percent percentageOf(@NonNull final Money whole)
{
assertCurrencyIdMatching(whole);
return Percent.of(toBigDecimal(), whole.toBigDecimal());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\Money.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ProducerTemplate producerTemplate()
{
return camelContext.createProducerTemplate();
}
@Bean
public CustomRouteController customRouteController()
{
return new CustomRouteController(this.camelContext);
}
@Bean
CamelContextConfiguration contextConfiguration(
@NonNull final MetasfreshAuthProvider metasfreshAuthProvider,
@NonNull final CustomRouteController customRouteController,
@NonNull final ProducerTemplate producerTemplate
)
{
return new CamelContextConfiguration()
{
@Override
public void beforeApplicationStart(final CamelContext camelContext)
{
camelContext.setAutoStartup(false);
final Environment env = context.getEnvironment();
logger.log(Level.INFO, "Configured RabbitMQ hostname:port is {}:{}", env.getProperty("camel.component.rabbitmq.hostname"), env.getProperty("camel.component.rabbitmq.port-number")); | final String metasfreshAPIBaseURL = context.getEnvironment().getProperty(ExternalSystemCamelConstants.MF_API_BASE_URL_PROPERTY);
if (Check.isBlank(metasfreshAPIBaseURL))
{
throw new RuntimeException("Missing mandatory property! property = " + ExternalSystemCamelConstants.MF_API_BASE_URL_PROPERTY);
}
camelContext.getManagementStrategy()
.addEventNotifier(new MetasfreshAuthorizationTokenNotifier(metasfreshAuthProvider, metasfreshAPIBaseURL, customRouteController, producerTemplate));
camelContext.getManagementStrategy()
.addEventNotifier(new AuditEventNotifier(producerTemplate));
}
@Override
public void afterApplicationStart(final CamelContext camelContext)
{
customRouteController().startAlwaysRunningRoutes();
producerTemplate
.sendBody("direct:" + CUSTOM_TO_MF_ROUTE_ID, "Trigger external system authentication!");
}
};
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\AppConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SettBizException extends BizException {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(SettBizException.class);
public static final SettBizException SETT_STATUS_ERROR = new SettBizException(10010001, "结算状态错误");
public SettBizException() {
}
public SettBizException(int code, String msgFormat, Object... args) {
super(code, msgFormat, args);
}
public SettBizException(int code, String msg) {
super(code, msg);
} | /**
* 实例化异常
*
* @param msgFormat
* @param args
* @return
*/
public SettBizException newInstance(String msgFormat, Object... args) {
return new SettBizException(this.code, msgFormat, args);
}
public SettBizException print() {
LOG.info("==>BizException, code:" + this.code + ", msg:" + this.msg);
return this;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\exception\SettBizException.java | 2 |
请完成以下Java代码 | public String getCustomPropertiesResolverImplementationType() {
return customPropertiesResolverImplementationType;
}
public void setCustomPropertiesResolverImplementationType(String customPropertiesResolverImplementationType) {
this.customPropertiesResolverImplementationType = customPropertiesResolverImplementationType;
}
public String getCustomPropertiesResolverImplementation() {
return customPropertiesResolverImplementation;
}
public void setCustomPropertiesResolverImplementation(String customPropertiesResolverImplementation) {
this.customPropertiesResolverImplementation = customPropertiesResolverImplementation;
}
public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance;
}
public ActivitiListener clone() {
ActivitiListener clone = new ActivitiListener(); | clone.setValues(this);
return clone;
}
public void setValues(ActivitiListener otherListener) {
setEvent(otherListener.getEvent());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ActivitiListener.java | 1 |
请完成以下Java代码 | public Flux<Map<String, Object>> handleSubscription(Map<String, Object> payload) {
return handleInternal(payload)
.flatMapMany((response) -> {
if (response.getData() instanceof Publisher) {
Publisher<ExecutionResult> publisher = response.getData();
return Flux.from(publisher).map(ExecutionResult::toSpecification);
}
else if (response.isValid()) {
return Flux.error(new InvalidException(
"Expected a Publisher for a subscription operation. " +
"This is either a server error or the operation is not a subscription"));
}
String errorData = encodeErrors(response).toString(StandardCharsets.UTF_8);
return Flux.error(new RejectedException(errorData));
}); | }
private Mono<RSocketGraphQlResponse> handleInternal(Map<String, Object> payload) {
String requestId = this.idGenerator.generateId().toString();
return this.executionChain.next(new RSocketGraphQlRequest(payload, requestId, null));
}
@SuppressWarnings("unchecked")
private DataBuffer encodeErrors(RSocketGraphQlResponse response) {
return ((Encoder<List<GraphQLError>>) this.jsonEncoder).encodeValue(
response.getExecutionResult().getErrors(),
DefaultDataBufferFactory.sharedInstance, LIST_TYPE, MimeTypeUtils.APPLICATION_JSON, null);
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\GraphQlRSocketHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static final class SqlSelect
{
private final String sql;
private final ImmutableList<TableNameAndAlias> tableNameAndAliases;
@Builder
private SqlSelect(
@NonNull final String sql,
@NonNull @Singular final ImmutableList<TableNameAndAlias> tableNameAndAliases)
{
this.sql = sql;
this.tableNameAndAliases = tableNameAndAliases;
}
public boolean hasWhereClause()
{
return sql.indexOf(" WHERE ") >= 0;
}
public String getFirstTableAliasOrTableName()
{
if (tableNameAndAliases.isEmpty()) // TODO check if we still need this check!
{
return ""; | }
return tableNameAndAliases.get(0).getAliasOrTableName();
}
public String getFirstTableNameOrEmpty()
{
if (tableNameAndAliases.isEmpty())
{
return "";
}
return tableNameAndAliases.get(0).getTableName();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\ParsedSql.java | 2 |
请完成以下Java代码 | public class BpmnParser extends AbstractModelParser {
private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
public BpmnParser() {
this.schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
addSchema(BPMN20_NS, createSchema(BPMN_20_SCHEMA_LOCATION, BpmnParser.class.getClassLoader()));
}
@Override
protected void configureFactory(DocumentBuilderFactory dbf) {
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
dbf.setAttribute(JAXP_SCHEMA_SOURCE, ReflectUtil.getResource(BPMN_20_SCHEMA_LOCATION, BpmnParser.class.getClassLoader()).toString());
super.configureFactory(dbf);
} | @Override
protected BpmnModelInstanceImpl createModelInstance(DomDocument document) {
return new BpmnModelInstanceImpl((ModelImpl) Bpmn.INSTANCE.getBpmnModel(), Bpmn.INSTANCE.getBpmnModelBuilder(), document);
}
@Override
public BpmnModelInstanceImpl parseModelFromStream(InputStream inputStream) {
return (BpmnModelInstanceImpl) super.parseModelFromStream(inputStream);
}
@Override
public BpmnModelInstanceImpl getEmptyModel() {
return (BpmnModelInstanceImpl) super.getEmptyModel();
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\BpmnParser.java | 1 |
请完成以下Java代码 | public MContainer getParent()
{
if (m_parent == null)
m_parent = new MContainer (getCtx(), getCM_Container_ID(), get_TrxName());
return m_parent;
/** No reason to do this ?? - should never return null - always there - JJ
int[] thisContainer = MContainer.getAllIDs("CM_Container","CM_Container_ID=" + this.getCM_Container_ID(), get_TrxName());
if (thisContainer != null)
{
if (thisContainer.length==1)
return new MContainer(getCtx(), thisContainer[0], get_TrxName());
}
return null;
**/
} // getContainer
/**
* After Save.
* Insert
* - create / update index
* @param newRecord insert
* @param success save success
* @return true if saved
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
reIndex(newRecord); | return success;
} // afterSave
/**
* reIndex
* @param newRecord
*/
public void reIndex(boolean newRecord)
{
int CMWebProjectID = 0;
if (getParent()!=null)
CMWebProjectID = getParent().getCM_WebProject_ID();
String [] toBeIndexed = new String[3];
toBeIndexed[0] = this.getName();
toBeIndexed[1] = this.getDescription();
toBeIndexed[2] = this.getContentHTML();
MIndex.reIndex (newRecord, toBeIndexed, getCtx(),
getAD_Client_ID(), get_Table_ID(), get_ID(), CMWebProjectID, this.getUpdated());
} // reIndex
} // MContainerElement | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MContainerElement.java | 1 |
请完成以下Java代码 | class M_HU_Item_SnapshotHandler extends AbstractSnapshotHandler<I_M_HU_Item, I_M_HU_Item_Snapshot, I_M_HU>
{
M_HU_Item_SnapshotHandler(final AbstractSnapshotHandler<?, ?, ?> parentHandler)
{
super(parentHandler);
}
@Override
protected void createSnapshotsByParentIds(final Set<Integer> huIds)
{
query(I_M_HU_Item.class)
.addInArrayOrAllFilter(I_M_HU_Item.COLUMN_M_HU_ID, huIds)
.create()
.insertDirectlyInto(I_M_HU_Item_Snapshot.class)
.mapCommonColumns()
.mapColumnToConstant(I_M_HU_Item_Snapshot.COLUMNNAME_Snapshot_UUID, getSnapshotId())
.execute();
}
@Override
protected Map<Integer, I_M_HU_Item_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU hu)
{
return query(I_M_HU_Item_Snapshot.class)
.addEqualsFilter(I_M_HU_Item_Snapshot.COLUMN_M_HU_ID, hu.getM_HU_ID())
.addEqualsFilter(I_M_HU_Item_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId())
.create()
.map(I_M_HU_Item_Snapshot.class, snapshot2ModelIdFunction);
}
@Override
protected Map<Integer, I_M_HU_Item> retrieveModelsByParent(final I_M_HU hu)
{
return query(I_M_HU_Item.class)
.addEqualsFilter(I_M_HU_Item.COLUMN_M_HU_ID, hu.getM_HU_ID())
.create()
.mapById(I_M_HU_Item.class);
}
@Override
protected I_M_HU_Item_Snapshot retrieveModelSnapshot(final I_M_HU_Item huItem)
{
return query(I_M_HU_Item_Snapshot.class)
.addEqualsFilter(I_M_HU_Item_Snapshot.COLUMN_M_HU_Item_ID, huItem.getM_HU_Item_ID())
.addEqualsFilter(I_M_HU_Item_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId())
.create()
.firstOnlyNotNull(I_M_HU_Item_Snapshot.class); | }
@Override
protected void restoreChildrenFromSnapshots(I_M_HU_Item huItem)
{
final M_HU_SnapshotHandler includedHUSnapshotHandler = new M_HU_SnapshotHandler(this);
includedHUSnapshotHandler.restoreModelsFromSnapshotsByParent(huItem);
final M_HU_Item_Storage_SnapshotHandler huItemStorageSnapshotHandler = new M_HU_Item_Storage_SnapshotHandler(this);
huItemStorageSnapshotHandler.restoreModelsFromSnapshotsByParent(huItem);
}
@Override
protected void restoreModelWhenSnapshotIsMissing(final I_M_HU_Item model)
{
// shall not happen because we are NEVER deleting an HU Item
throw new HUException("Cannot restore " + model + " because snapshot is missing");
}
@Override
protected int getModelId(final I_M_HU_Item_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU_Item_ID();
}
@Override
protected I_M_HU_Item getModel(I_M_HU_Item_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU_Item();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_Item_SnapshotHandler.java | 1 |
请完成以下Java代码 | public class EitherDemo {
public static Object[] computeWithoutEitherUsingArray(int marks) {
Object[] results = new Object[2];
if (marks < 85) {
results[0] = "Marks not acceptable";
} else {
results[1] = marks;
}
return results;
}
public static Map<String, Object> computeWithoutEitherUsingMap(int marks) {
Map<String, Object> results = new HashMap<>();
if (marks < 85) { | results.put("FAILURE", "Marks not acceptable");
} else {
results.put("SUCCESS", marks);
}
return results;
}
static Either<String, Integer> computeWithEither(int marks) {
if (marks < 85) {
return Either.left("Marks not acceptable");
} else {
return Either.right(marks);
}
}
} | repos\tutorials-master\vavr-modules\vavr-2\src\main\java\com\baeldung\vavr\either\EitherDemo.java | 1 |
请完成以下Java代码 | public LicenseKeyDataImpl getLicenseKeyFromDiagnostics() {
DiagnosticsRegistry diagnosticsRegistry = ((ProcessEngineConfigurationImpl) processEngineConfiguration).getDiagnosticsRegistry();
if (diagnosticsRegistry != null) {
return diagnosticsRegistry.getLicenseKey();
}
return null;
}
public void clearDiagnosticsData() {
DiagnosticsRegistry diagnosticsRegistry = ((ProcessEngineConfigurationImpl) processEngineConfiguration).getDiagnosticsRegistry();
if (diagnosticsRegistry != null) {
diagnosticsRegistry.clear();
}
MetricsRegistry metricsRegistry = ((ProcessEngineConfigurationImpl) processEngineConfiguration).getMetricsRegistry();
if(metricsRegistry != null) {
metricsRegistry.clearDiagnosticsMetrics();
}
deleteMetrics(null);
}
protected class DbSchemaUpgradeCmd implements Command<String> {
protected Connection connection;
protected String catalog;
protected String schema;
public DbSchemaUpgradeCmd(Connection connection, String catalog, String schema) {
this.connection = connection;
this.catalog = catalog;
this.schema = schema;
}
@Override | public String execute(CommandContext commandContext) {
commandContext.getAuthorizationManager().checkCamundaAdmin();
DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) commandContext.getSessionFactories().get(DbSqlSession.class);
DbSqlSession dbSqlSession = dbSqlSessionFactory.openSession(connection, catalog, schema);
commandContext.getSessions().put(DbSqlSession.class, dbSqlSession);
dbSqlSession.dbSchemaUpdate();
return "";
}
}
protected class GetRegisteredDeploymentsCmd implements Command<Set<String>> {
@Override
public Set<String> execute(CommandContext commandContext) {
commandContext.getAuthorizationManager().checkCamundaAdminOrPermission(CommandChecker::checkReadRegisteredDeployments);
Set<String> registeredDeployments = Context.getProcessEngineConfiguration().getRegisteredDeployments();
return new HashSet<>(registeredDeployments);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ManagementServiceImpl.java | 1 |
请完成以下Java代码 | public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Counter.
@param Counter
Count Value
*/
public void setCounter (int Counter)
{
throw new IllegalArgumentException ("Counter is virtual column"); }
/** Get Counter.
@return Count Value
*/
public int getCounter ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Counter);
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 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 Page URL.
@param PageURL Page URL */
public void setPageURL (String PageURL)
{ | set_Value (COLUMNNAME_PageURL, PageURL);
}
/** Get Page URL.
@return Page URL */
public String getPageURL ()
{
return (String)get_Value(COLUMNNAME_PageURL);
}
/** Set Counter Count.
@param W_CounterCount_ID
Web Counter Count Management
*/
public void setW_CounterCount_ID (int W_CounterCount_ID)
{
if (W_CounterCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID));
}
/** Get Counter Count.
@return Web Counter Count Management
*/
public int getW_CounterCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_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_W_CounterCount.java | 1 |
请完成以下Java代码 | public void setPP_Product_Planning_ID (final int PP_Product_Planning_ID)
{
if (PP_Product_Planning_ID < 1)
set_Value (COLUMNNAME_PP_Product_Planning_ID, null);
else
set_Value (COLUMNNAME_PP_Product_Planning_ID, PP_Product_Planning_ID);
}
@Override
public int getPP_Product_Planning_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyEntered (final BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEnteredTU (final @Nullable BigDecimal QtyEnteredTU)
{
set_Value (COLUMNNAME_QtyEnteredTU, QtyEnteredTU);
}
@Override
public BigDecimal getQtyEnteredTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyProcessed (final BigDecimal QtyProcessed)
{
set_Value (COLUMNNAME_QtyProcessed, QtyProcessed);
} | @Override
public BigDecimal getQtyProcessed()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyProcessed);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToProcess (final BigDecimal QtyToProcess)
{
set_Value (COLUMNNAME_QtyToProcess, QtyToProcess);
}
@Override
public BigDecimal getQtyToProcess()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProcess);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSupplyDate (final java.sql.Timestamp SupplyDate)
{
set_Value (COLUMNNAME_SupplyDate, SupplyDate);
}
@Override
public java.sql.Timestamp getSupplyDate()
{
return get_ValueAsTimestamp(COLUMNNAME_SupplyDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_Order_Candidate.java | 1 |
请完成以下Java代码 | public class MathUtility
{
public static int sum(int... var)
{
int sum = 0;
for (int x : var)
{
sum += x;
}
return sum;
}
public static float sum(float... var)
{
float sum = 0;
for (float x : var)
{
sum += x;
}
return sum;
}
public static double percentage(double current, double total)
{
return current / total * 100.;
}
public static double average(double array[])
{
double sum = 0;
for (int i = 0; i < array.length; i++)
sum += array[i];
return sum / array.length;
}
/**
* 使用log-sum-exp技巧来归一化一组对数值
*
* @param predictionScores
*/
public static void normalizeExp(Map<String, Double> predictionScores)
{
Set<Map.Entry<String, Double>> entrySet = predictionScores.entrySet();
double max = Double.NEGATIVE_INFINITY;
for (Map.Entry<String, Double> entry : entrySet)
{
max = Math.max(max, entry.getValue());
}
double sum = 0.0;
//通过减去最大值防止浮点数溢出
for (Map.Entry<String, Double> entry : entrySet)
{
Double value = Math.exp(entry.getValue() - max);
entry.setValue(value);
sum += value;
}
if (sum != 0.0)
{
for (Map.Entry<String, Double> entry : entrySet)
{
predictionScores.put(entry.getKey(), entry.getValue() / sum);
}
} | }
public static void normalizeExp(double[] predictionScores)
{
double max = Double.NEGATIVE_INFINITY;
for (double value : predictionScores)
{
max = Math.max(max, value);
}
double sum = 0.0;
//通过减去最大值防止浮点数溢出
for (int i = 0; i < predictionScores.length; i++)
{
predictionScores[i] = Math.exp(predictionScores[i] - max);
sum += predictionScores[i];
}
if (sum != 0.0)
{
for (int i = 0; i < predictionScores.length; i++)
{
predictionScores[i] /= sum;
}
}
}
/**
* 从一个词到另一个词的词的花费
*
* @param from 前面的词
* @param to 后面的词
* @return 分数
*/
public static double calculateWeight(Vertex from, Vertex to)
{
int fFrom = from.getAttribute().totalFrequency;
int fBigram = CoreBiGramTableDictionary.getBiFrequency(from.wordID, to.wordID);
int fTo = to.getAttribute().totalFrequency;
// logger.info(String.format("%5s frequency:%6d, %s fBigram:%3d, weight:%.2f", from.word, frequency, from.word + "@" + to.word, fBigram, value));
return -Math.log(Predefine.lambda * (Predefine.myu * fBigram / (fFrom + 1) + 1 - Predefine.myu) + (1 - Predefine.lambda) * fTo / Predefine.TOTAL_FREQUENCY);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\MathUtility.java | 1 |
请完成以下Java代码 | public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Type AD_Reference_ID=53245 */
public static final int TYPE_AD_Reference_ID=53245;
/** Concept = C */
public static final String TYPE_Concept = "C";
/** Rule Engine = E */
public static final String TYPE_RuleEngine = "E";
/** Information = I */
public static final String TYPE_Information = "I";
/** Reference = R */
public static final String TYPE_Reference = "R";
/** Set Type.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
public void setType (String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Type.
@return Type of Validation (SQL, Java Script, Java Language)
*/
public String getType ()
{
return (String)get_Value(COLUMNNAME_Type);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
} | /** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getValue());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.