instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class CalculatedFieldManagerActor extends AbstractCalculatedFieldActor {
private final CalculatedFieldManagerMessageProcessor processor;
public CalculatedFieldManagerActor(ActorSystemContext systemContext, TenantId tenantId) {
super(systemContext, tenantId);
this.processor = new CalculatedFieldManagerMessageProcessor(systemContext, tenantId);
}
@Override
public void init(TbActorCtx ctx) throws TbActorException {
super.init(ctx);
log.debug("[{}] Starting CF manager actor.", processor.tenantId);
try {
processor.init(ctx);
log.debug("[{}] CF manager actor started.", processor.tenantId);
} catch (Exception e) {
log.warn("[{}] Unknown failure", processor.tenantId, e);
throw new TbActorException("Failed to initialize manager actor", e);
}
}
@Override
public void destroy(TbActorStopReason stopReason, Throwable cause) throws TbActorException {
log.debug("[{}] Stopping CF manager actor.", processor.tenantId);
processor.stop();
}
@Override
protected boolean doProcessCfMsg(ToCalculatedFieldSystemMsg msg) throws CalculatedFieldException {
switch (msg.getMsgType()) {
case CF_PARTITIONS_CHANGE_MSG:
processor.onPartitionChange((CalculatedFieldPartitionChangeMsg) msg); | break;
case CF_CACHE_INIT_MSG:
processor.onCacheInitMsg((CalculatedFieldCacheInitMsg) msg);
break;
case CF_STATE_RESTORE_MSG:
processor.onStateRestoreMsg((CalculatedFieldStateRestoreMsg) msg);
break;
case CF_STATE_PARTITION_RESTORE_MSG:
processor.onStatePartitionRestoreMsg((CalculatedFieldStatePartitionRestoreMsg) msg);
break;
case CF_ENTITY_LIFECYCLE_MSG:
processor.onEntityLifecycleMsg((CalculatedFieldEntityLifecycleMsg) msg);
break;
case CF_ENTITY_ACTION_EVENT_MSG:
processor.onEntityActionEventMsg((CalculatedFieldEntityActionEventMsg) msg);
break;
case CF_TELEMETRY_MSG:
processor.onTelemetryMsg((CalculatedFieldTelemetryMsg) msg);
break;
case CF_LINKED_TELEMETRY_MSG:
processor.onLinkedTelemetryMsg((CalculatedFieldLinkedTelemetryMsg) msg);
break;
default:
return false;
}
return true;
}
@Override
void logProcessingException(Exception e) {
log.warn("[{}] Processing failure", tenantId, e);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\calculatedField\CalculatedFieldManagerActor.java | 1 |
请完成以下Java代码 | protected void parseProcessArchive(Element element, List<ProcessArchiveXml> parsedProcessArchives) {
ProcessArchiveXmlImpl processArchive = new ProcessArchiveXmlImpl();
processArchive.setName(element.attribute(NAME));
processArchive.setTenantId(element.attribute(TENANT_ID));
List<String> processResourceNames = new ArrayList<String>();
Map<String, String> properties = new HashMap<String, String>();
for (Element childElement : element.elements()) {
if(PROCESS_ENGINE.equals(childElement.getTagName())) {
processArchive.setProcessEngineName(childElement.getText());
} else if(PROCESS.equals(childElement.getTagName()) || RESOURCE.equals(childElement.getTagName())) {
processResourceNames.add(childElement.getText());
} else if(PROPERTIES.equals(childElement.getTagName())) {
parseProperties(childElement, properties);
}
}
// set properties
processArchive.setProperties(properties); | // add collected resource names.
processArchive.setProcessResourceNames(processResourceNames);
// add process archive to list of parsed archives.
parsedProcessArchives.add(processArchive);
}
public ProcessesXml getProcessesXml() {
return processesXml;
}
@Override
public ProcessesXmlParse sourceUrl(URL url) {
super.sourceUrl(url);
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\metadata\ProcessesXmlParse.java | 1 |
请完成以下Java代码 | public void removeActionListener(final ActionListener listener)
{
m_text.removeActionListener(listener);
} // removeActionListener
/**
* Set Field/WindowNo
*
* @param mField field
*/
@Override
public void setField(final GridField mField)
{
m_field = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
/** Grid Field */
private GridField m_field = null;
/**
* Get Field
*
* @return gridField
*/
@Override
public GridField getField()
{
return m_field;
} // getField
@Override
public void keyPressed(final KeyEvent e)
{
}
@Override
public void keyTyped(final KeyEvent e)
{
}
/**
* Key Released. if Escape Restore old Text
*
* @param e event | * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
@Override
public void keyReleased(final KeyEvent e)
{
if (LogManager.isLevelFinest())
{
log.trace("Key=" + e.getKeyCode() + " - " + e.getKeyChar() + " -> " + m_text.getText());
}
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
m_text.setText(m_initialText);
}
else if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED)
{
return;
}
m_setting = true;
try
{
String clear = m_text.getText();
if (clear.length() > m_fieldLength)
{
clear = clear.substring(0, m_fieldLength);
}
fireVetoableChange(m_columnName, m_oldText, clear);
}
catch (final PropertyVetoException pve)
{
}
m_setting = false;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VFile | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VFile.java | 1 |
请完成以下Java代码 | public class TenantCheck implements Serializable {
private static final long serialVersionUID = 1L;
/**
* If <code>true</code> then the process engine performs tenant checks to
* ensure that the query only access data that belongs to one of the
* authenticated tenant ids.
*/
protected boolean isTenantCheckEnabled = true;
/** the ids of the authenticated tenants */
protected List<String> authTenantIds = new ArrayList<String>();
public boolean isTenantCheckEnabled() {
return isTenantCheckEnabled;
}
/** is used by myBatis */ | public boolean getIsTenantCheckEnabled() {
return isTenantCheckEnabled;
}
public void setTenantCheckEnabled(boolean isTenantCheckEnabled) {
this.isTenantCheckEnabled = isTenantCheckEnabled;
}
public List<String> getAuthTenantIds() {
return authTenantIds;
}
public void setAuthTenantIds(List<String> tenantIds) {
this.authTenantIds = tenantIds;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\TenantCheck.java | 1 |
请完成以下Java代码 | public JacksonJsonDeserializer<T> deserializer() {
return this.jsonDeserializer;
}
/**
* Copies this serde with same configuration, except new target type is used.
* @param newTargetType type reference forced for serialization, and used as default for deserialization, not null
* @param <X> new deserialization result type and serialization source type
* @return new instance of serde with type changes
*/
public <X> JacksonJsonSerde<X> copyWithType(Class<? super X> newTargetType) {
return new JacksonJsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
/**
* Copies this serde with same configuration, except new target type reference is used.
* @param newTargetType type reference forced for serialization, and used as default for deserialization, not null
* @param <X> new deserialization result type and serialization source type
* @return new instance of serde with type changes
*/
public <X> JacksonJsonSerde<X> copyWithType(TypeReference<? super X> newTargetType) {
return new JacksonJsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
/**
* Copies this serde with same configuration, except new target java type is used.
* @param newTargetType java type forced for serialization, and used as default for deserialization, not null
* @param <X> new deserialization result type and serialization source type
* @return new instance of serde with type changes
*/
public <X> JacksonJsonSerde<X> copyWithType(JavaType newTargetType) {
return new JacksonJsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
// Fluent API
/**
* Designate this Serde for serializing/deserializing keys (default is values).
* @return the serde.
*/
public JacksonJsonSerde<T> forKeys() {
this.jsonSerializer.forKeys();
this.jsonDeserializer.forKeys();
return this;
}
/**
* Configure the serializer to not add type information.
* @return the serde.
*/
public JacksonJsonSerde<T> noTypeInfo() {
this.jsonSerializer.noTypeInfo();
return this;
}
/**
* Don't remove type information headers after deserialization.
* @return the serde. | */
public JacksonJsonSerde<T> dontRemoveTypeHeaders() {
this.jsonDeserializer.dontRemoveTypeHeaders();
return this;
}
/**
* Ignore type information headers and use the configured target class.
* @return the serde.
*/
public JacksonJsonSerde<T> ignoreTypeHeaders() {
this.jsonDeserializer.ignoreTypeHeaders();
return this;
}
/**
* Use the supplied {@link JacksonJavaTypeMapper}.
* @param mapper the mapper.
* @return the serde.
*/
public JacksonJsonSerde<T> typeMapper(JacksonJavaTypeMapper mapper) {
this.jsonSerializer.setTypeMapper(mapper);
this.jsonDeserializer.setTypeMapper(mapper);
return this;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JacksonJsonSerde.java | 1 |
请完成以下Java代码 | public static MSalesRegion get (Properties ctx, int C_SalesRegion_ID)
{
Integer key = new Integer (C_SalesRegion_ID);
MSalesRegion retValue = (MSalesRegion) s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MSalesRegion (ctx, C_SalesRegion_ID, null);
if (retValue.get_ID () != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/** Cache */
private static CCache<Integer,MSalesRegion> s_cache = new CCache<Integer,MSalesRegion>("C_SalesRegion", 10);
/**************************************************************************
* Default Constructor
* @param ctx context
* @param C_SalesRegion_ID id
* @param trxName transaction
*/
public MSalesRegion (Properties ctx, int C_SalesRegion_ID, String trxName)
{
super (ctx, C_SalesRegion_ID, trxName);
} // MSalesRegion
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MSalesRegion (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MSalesRegion
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
if (getAD_Org_ID() != 0)
setAD_Org_ID(0);
return true;
} // beforeSave
/**
* After Save.
* Insert
* - create tree
* @param newRecord insert | * @param success save success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
if (newRecord)
insert_Tree(MTree_Base.TREETYPE_SalesRegion);
// Value/Name change
if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name")))
MAccount.updateValueDescription(getCtx(), "C_SalesRegion_ID=" + getC_SalesRegion_ID(), get_TrxName());
return true;
} // afterSave
/**
* After Delete
* @param success
* @return deleted
*/
protected boolean afterDelete (boolean success)
{
if (success)
delete_Tree(MTree_Base.TREETYPE_SalesRegion);
return success;
} // afterDelete
} // MSalesRegion | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSalesRegion.java | 1 |
请完成以下Java代码 | public Definitions newInstance(ModelTypeInstanceContext instanceContext) {
return new DefinitionsImpl(instanceContext);
}
});
expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.defaultValue("http://www.omg.org/spec/FEEL/20140401")
.build();
typeLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_LANGUAGE)
.defaultValue("http://www.omg.org/spec/FEEL/20140401")
.build();
namespaceAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAMESPACE)
.required()
.build();
exporterAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER)
.build();
exporterVersionAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER_VERSION)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
importCollection = sequenceBuilder.elementCollection(Import.class)
.build();
itemDefinitionCollection = sequenceBuilder.elementCollection(ItemDefinition.class) | .build();
drgElementCollection = sequenceBuilder.elementCollection(DrgElement.class)
.build();
artifactCollection = sequenceBuilder.elementCollection(Artifact.class)
.build();
elementCollectionCollection = sequenceBuilder.elementCollection(ElementCollection.class)
.build();
businessContextElementCollection = sequenceBuilder.elementCollection(BusinessContextElement.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DefinitionsImpl.java | 1 |
请完成以下Java代码 | public static ProcessDefinitionSuspensionStateConfiguration fromJson(JsonObject jsonObject) {
ProcessDefinitionSuspensionStateConfiguration config = new ProcessDefinitionSuspensionStateConfiguration();
config.by = JsonUtil.getString(jsonObject, JOB_HANDLER_CFG_BY);
if (jsonObject.has(JOB_HANDLER_CFG_PROCESS_DEFINITION_ID)) {
config.processDefinitionId = JsonUtil.getString(jsonObject, JOB_HANDLER_CFG_PROCESS_DEFINITION_ID);
}
if (jsonObject.has(JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY)) {
config.processDefinitionKey = JsonUtil.getString(jsonObject, JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY);
}
if (jsonObject.has(JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID)) {
config.isTenantIdSet = true;
if (!JsonUtil.isNull(jsonObject, JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID)) {
config.tenantId = JsonUtil.getString(jsonObject, JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID);
}
}
if (jsonObject.has(JOB_HANDLER_CFG_INCLUDE_PROCESS_INSTANCES)) {
config.includeProcessInstances = JsonUtil.getBoolean(jsonObject, JOB_HANDLER_CFG_INCLUDE_PROCESS_INSTANCES);
}
return config;
}
public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionId(String processDefinitionId, boolean includeProcessInstances) {
ProcessDefinitionSuspensionStateConfiguration configuration = new ProcessDefinitionSuspensionStateConfiguration();
configuration.by = JOB_HANDLER_CFG_PROCESS_DEFINITION_ID;
configuration.processDefinitionId = processDefinitionId;
configuration.includeProcessInstances = includeProcessInstances;
return configuration;
} | public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionKey(String processDefinitionKey, boolean includeProcessInstances) {
ProcessDefinitionSuspensionStateConfiguration configuration = new ProcessDefinitionSuspensionStateConfiguration();
configuration.by = JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY;
configuration.processDefinitionKey = processDefinitionKey;
configuration.includeProcessInstances = includeProcessInstances;
return configuration;
}
public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionKeyAndTenantId(String processDefinitionKey, String tenantId, boolean includeProcessInstances) {
ProcessDefinitionSuspensionStateConfiguration configuration = byProcessDefinitionKey(processDefinitionKey, includeProcessInstances);
configuration.isTenantIdSet = true;
configuration.tenantId = tenantId;
return configuration;
}
}
public void onDelete(ProcessDefinitionSuspensionStateConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerChangeProcessDefinitionSuspensionStateJobHandler.java | 1 |
请完成以下Java代码 | public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getDivisionId() {
return divisionId;
}
public void setDivisionId(Integer divisionId) {
this.divisionId = divisionId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime; | }
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDisabled() {
return disabled;
}
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public Integer getIsLdap() {
return isLdap;
}
public void setIsLdap(Integer isLdap) {
this.isLdap = isLdap;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
} | repos\springBoot-master\springboot-jpa\src\main\java\com\us\example\bean\User.java | 1 |
请完成以下Java代码 | public class BinaryTreeModel {
private Object value;
private BinaryTreeModel left;
private BinaryTreeModel right;
public BinaryTreeModel(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public BinaryTreeModel getLeft() {
return left; | }
public void setLeft(BinaryTreeModel left) {
this.left = left;
}
public BinaryTreeModel getRight() {
return right;
}
public void setRight(BinaryTreeModel right) {
this.right = right;
}
} | repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\printbinarytree\BinaryTreeModel.java | 1 |
请完成以下Java代码 | public class SampleListener implements MessageListener {
private JmsTemplate jmsTemplate;
private Queue queue;
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void setQueue(Queue queue) {
this.queue = queue;
}
public void onMessage(Message message) {
if (message instanceof TextMessage) {
try {
String msg = ((TextMessage) message).getText(); | System.out.println("Received message: " + msg);
if (msg == null) {
throw new IllegalArgumentException("Null value received...");
}
} catch (JMSException ex) {
throw new RuntimeException(ex);
}
}
}
public Employee receiveMessage() throws JMSException {
Map map = (Map) this.jmsTemplate.receiveAndConvert();
return new Employee((String) map.get("name"), (Integer) map.get("age"));
}
} | repos\tutorials-master\messaging-modules\spring-jms\src\main\java\com\baeldung\spring\jms\SampleListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String edit(HttpServletRequest request, @PathVariable("newsId") Long newsId) {
request.setAttribute("path", "edit");
News news = newsService.queryNewsById(newsId);
if (news == null) {
return "error/error_400";
}
request.setAttribute("news", news);
request.setAttribute("categories", categoryService.getAllCategories());
return "admin/edit";
}
@PostMapping("/news/update")
@ResponseBody
public Result update(@RequestParam("newsId") Long newsId,
@RequestParam("newsTitle") String newsTitle,
@RequestParam("newsCategoryId") Long newsCategoryId,
@RequestParam("newsContent") String newsContent,
@RequestParam("newsCoverImage") String newsCoverImage,
@RequestParam("newsStatus") Byte newsStatus) {
if (!StringUtils.hasText(newsTitle)) {
return ResultGenerator.genFailResult("请输入文章标题");
}
if (newsTitle.trim().length() > 150) {
return ResultGenerator.genFailResult("标题过长");
}
if (!StringUtils.hasText(newsContent)) {
return ResultGenerator.genFailResult("请输入文章内容");
}
if (newsContent.trim().length() > 100000) {
return ResultGenerator.genFailResult("文章内容过长");
}
if (!StringUtils.hasText(newsCoverImage)) {
return ResultGenerator.genFailResult("封面图不能为空");
}
News news = new News();
news.setNewsId(newsId);
news.setNewsCategoryId(newsCategoryId); | news.setNewsContent(newsContent);
news.setNewsCoverImage(newsCoverImage);
news.setNewsStatus(newsStatus);
news.setNewsTitle(newsTitle);
String updateResult = newsService.updateNews(news);
if ("success".equals(updateResult)) {
return ResultGenerator.genSuccessResult("修改成功");
} else {
return ResultGenerator.genFailResult(updateResult);
}
}
@PostMapping("/news/delete")
@ResponseBody
public Result delete(@RequestBody Integer[] ids) {
if (ids.length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (newsService.deleteBatch(ids)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\admin\NewsController.java | 2 |
请完成以下Java代码 | public class SqlParamsInliner
{
private final boolean failOnError;
@Builder
private SqlParamsInliner(
final boolean failOnError)
{
this.failOnError = failOnError;
}
public String inline(@NonNull final String sql, @Nullable final Object... params)
{
final List<Object> paramsList = params != null && params.length > 0 ? Arrays.asList(params) : null;
return inline(sql, paramsList);
}
public String inline(@NonNull final String sql, @Nullable final List<Object> params)
{
try
{
return inline0(sql, params);
}
catch (final Exception ex)
{
//noinspection ConstantConditions
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("sql", sql)
.setParameter("sqlParams", params)
.appendParametersToMessage();
}
}
private String inline0(@NonNull final String sql, @Nullable final List<Object> params)
{
final int paramsCount = params != null ? params.size() : 0;
final int sqlLength = sql.length();
final StringBuilder sqlFinal = new StringBuilder(sqlLength);
boolean insideQuotes = false;
int nextParamIndex = 0;
for (int i = 0; i < sqlLength; i++)
{
final char ch = sql.charAt(i);
if (ch == '?')
{
if (insideQuotes)
{
sqlFinal.append(ch);
}
else
{
if (params != null && nextParamIndex < paramsCount)
{
sqlFinal.append(DB.TO_SQL(params.get(nextParamIndex)));
}
else
{
// error: parameter index is invalid
appendMissingParam(sqlFinal, nextParamIndex);
}
nextParamIndex++;
}
}
else if (ch == '\'')
{
sqlFinal.append(ch);
insideQuotes = !insideQuotes;
}
else | {
sqlFinal.append(ch);
}
}
if (params != null && nextParamIndex < paramsCount)
{
appendExceedingParams(sqlFinal, nextParamIndex, paramsCount, params);
}
return sqlFinal.toString();
}
private void appendMissingParam(
final StringBuilder sql,
final int missingParamIndexZeroBased)
{
final int missingParamIndexOneBased = missingParamIndexZeroBased + 1;
if (failOnError)
{
throw new AdempiereException("Missing SQL parameter with index=" + missingParamIndexOneBased);
}
sql.append("?missing").append(missingParamIndexOneBased).append("?");
}
private void appendExceedingParams(
final StringBuilder sql,
final int firstExceedingParamIndex,
final int paramsCount,
final List<Object> allParams)
{
if (failOnError)
{
throw new AdempiereException("Got more SQL params than needed: " + allParams.subList(firstExceedingParamIndex, allParams.size()));
}
sql.append(" -- Exceeding params: ");
boolean firstExceedingParam = true;
for (int i = firstExceedingParamIndex; i < paramsCount; i++)
{
if (firstExceedingParam)
{
firstExceedingParam = false;
}
else
{
sql.append(", ");
}
sql.append(DB.TO_SQL(allParams.get(i)));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\sql\SqlParamsInliner.java | 1 |
请完成以下Java代码 | public void dispose()
{
final ProcessPanel panel = this.panel;
if (panel != null)
{
panel.dispose();
this.panel = null;
}
super.dispose();
}
public boolean isDisposed()
{
final ProcessPanel panel = this.panel; | return panel == null || panel.isDisposed();
}
@Override
public void setVisible(final boolean visible)
{
super.setVisible(visible);
final ProcessPanel panel = this.panel;
if (panel != null)
{
panel.setVisible(visible);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessModalDialog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult add(@RequestBody MemberBrandAttention memberBrandAttention) {
int count = memberAttentionService.add(memberBrandAttention);
if(count>0){
return CommonResult.success(count);
}else{
return CommonResult.failed();
}
}
@ApiOperation("取消品牌关注")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(Long brandId) {
int count = memberAttentionService.delete(brandId);
if(count>0){
return CommonResult.success(count);
}else{
return CommonResult.failed();
}
}
@ApiOperation("分页查询当前用户品牌关注列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<MemberBrandAttention>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) { | Page<MemberBrandAttention> page = memberAttentionService.list(pageNum,pageSize);
return CommonResult.success(CommonPage.restPage(page));
}
@ApiOperation("根据品牌ID获取品牌关注详情")
@RequestMapping(value = "/detail", method = RequestMethod.GET)
@ResponseBody
public CommonResult<MemberBrandAttention> detail(@RequestParam Long brandId) {
MemberBrandAttention memberBrandAttention = memberAttentionService.detail(brandId);
return CommonResult.success(memberBrandAttention);
}
@ApiOperation("清空当前用户品牌关注列表")
@RequestMapping(value = "/clear", method = RequestMethod.POST)
@ResponseBody
public CommonResult clear() {
memberAttentionService.clear();
return CommonResult.success(null);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\MemberAttentionController.java | 2 |
请完成以下Spring Boot application配置 | spring:
ai:
mistralai:
api-key: ${MISTRAL_AI_API_KEY}
chat:
options:
model: mistral-small-latest
openai:
api-key: xxxx
chat. | enabled: true
embedding.enabled: true
chat.options.model: gpt-4o | repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final PlainContextAware localCtx = PlainContextAware.newWithThreadInheritedTrx(getCtx());
final Set<I_M_DiscountSchemaBreak_V> breaks = getProcessInfo().getSelectedIncludedRecords()
.stream()
.map(recordRef -> recordRef.getModel(localCtx, I_M_DiscountSchemaBreak_V.class))
.collect(ImmutableSet.toImmutableSet());
final Set<ProductId> products = new HashSet<ProductId>();
final Set<PricingConditionsId> pricingConditions = new HashSet<PricingConditionsId>();
breaks.forEach(record -> {
products.add(ProductId.ofRepoId(record.getM_Product_ID()));
//
pricingConditions.add(PricingConditionsId.ofRepoId(record.getM_DiscountSchema_ID()));
});
// run copy for each product separate
for (final ProductId product : products) | {
copyDiscountSchemaBreaks(pricingConditions, product);
};
return MSG_OK;
}
private void copyDiscountSchemaBreaks(final Set<PricingConditionsId> pricingConditions, ProductId product)
{
final ICompositeQueryFilter<I_M_DiscountSchemaBreak> queryFilter = Services.get(IQueryBL.class)
.createCompositeQueryFilter(I_M_DiscountSchemaBreak.class)
.setJoinAnd()
.addInArrayFilter(I_M_DiscountSchemaBreak.COLUMNNAME_M_DiscountSchema_ID, pricingConditions)
.addInArrayFilter(I_M_DiscountSchemaBreak.COLUMNNAME_M_Product_ID, product);
final boolean allowCopyToSameSchema = true;
final CopyDiscountSchemaBreaksRequest request = CopyDiscountSchemaBreaksRequest.builder()
.filter(queryFilter)
.pricingConditionsId(PricingConditionsId.ofRepoId(p_PricingConditionsId))
.productId(ProductId.ofRepoId(p_ProductId))
.allowCopyToSameSchema(allowCopyToSameSchema)
.direction(Direction.TargetSource)
.makeTargetAsSource(p_MakeTargetAsSource)
.build();
pricingConditionsRepo.copyDiscountSchemaBreaksWithProductId(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pricing\process\M_DiscountSchemaBreak_CopyToSelectedSchema_Product.java | 1 |
请完成以下Java代码 | public void clearContext() {
contextHolder.remove();
}
@Override
public SecurityContext getContext() {
return getDeferredContext().get();
}
@Override
public Supplier<SecurityContext> getDeferredContext() {
Supplier<SecurityContext> result = contextHolder.get();
if (result == null) {
SecurityContext context = createEmptyContext();
result = () -> context;
contextHolder.set(result);
}
return result;
}
@Override
public void setContext(SecurityContext context) {
Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
contextHolder.set(() -> context);
}
@Override | public void setDeferredContext(Supplier<SecurityContext> deferredContext) {
Assert.notNull(deferredContext, "Only non-null Supplier instances are permitted");
Supplier<SecurityContext> notNullDeferredContext = () -> {
SecurityContext result = deferredContext.get();
Assert.notNull(result, "A Supplier<SecurityContext> returned null and is not allowed.");
return result;
};
contextHolder.set(notNullDeferredContext);
}
@Override
public SecurityContext createEmptyContext() {
return new SecurityContextImpl();
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\context\InheritableThreadLocalSecurityContextHolderStrategy.java | 1 |
请完成以下Java代码 | protected void load() {
try {
byte[] bytes = engineClient.getLocalBinaryVariable(variableName, executionId);
setValue(bytes);
this.isLoaded = true;
} catch (EngineClientException e) {
throw LOG.handledEngineClientException("loading deferred file", e);
}
}
public boolean isLoaded() {
return isLoaded;
}
@Override
public InputStream getValue() {
if (!isLoaded()) {
load();
} | return super.getValue();
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public void setExecutionId(String executionId){
this.executionId = executionId;
};
public String getExecutionId() {
return executionId;
}
@Override
public String toString() {
return "DeferredFileValueImpl [mimeType=" + mimeType + ", filename=" + filename + ", type=" + type + ", "
+ "isTransient=" + isTransient + ", isLoaded=" + isLoaded + "]";
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\value\DeferredFileValueImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void persistAuthorWithBooksAndRemoveOneBookList() {
AuthorList alicia = new AuthorList();
alicia.setName("Alicia Tom");
alicia.setAge(38);
alicia.setGenre("Anthology");
AuthorList mark = new AuthorList();
mark.setName("Mark Janel");
mark.setAge(23);
mark.setGenre("Anthology");
BookList bookOfSwords = new BookList();
bookOfSwords.setIsbn("001-AT-MJ");
bookOfSwords.setTitle("The book of swords");
BookList oneDay = new BookList();
oneDay.setIsbn("002-AT-MJ");
oneDay.setTitle("One Day");
BookList headDown = new BookList();
headDown.setIsbn("001-AT");
headDown.setTitle("Head Down");
alicia.addBook(bookOfSwords);
mark.addBook(bookOfSwords);
alicia.addBook(oneDay);
mark.addBook(oneDay);
alicia.addBook(headDown);
authorListRepository.save(alicia);
authorListRepository.saveAndFlush(mark);
System.out.println("================================================");
System.out.println("Removing a book (List case) ...");
System.out.println("================================================");
alicia.removeBook(oneDay);
}
@Transactional
public void persistAuthorWithBooksAndRemoveOneBookSet() {
AuthorSet alicia = new AuthorSet();
alicia.setName("Alicia Tom");
alicia.setAge(38);
alicia.setGenre("Anthology");
AuthorSet mark = new AuthorSet();
mark.setName("Mark Janel");
mark.setAge(23);
mark.setGenre("Anthology");
BookSet bookOfSwords = new BookSet(); | bookOfSwords.setIsbn("001-AT-MJ");
bookOfSwords.setTitle("The book of swords");
BookSet oneDay = new BookSet();
oneDay.setIsbn("002-AT-MJ");
oneDay.setTitle("One Day");
BookSet headDown = new BookSet();
headDown.setIsbn("001-AT");
headDown.setTitle("Head Down");
alicia.addBook(bookOfSwords);
mark.addBook(bookOfSwords);
alicia.addBook(oneDay);
mark.addBook(oneDay);
alicia.addBook(headDown);
authorSetRepository.save(alicia);
authorSetRepository.saveAndFlush(mark);
System.out.println("================================================");
System.out.println("Removing a book (Set case) ...");
System.out.println("================================================");
alicia.removeBook(oneDay);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootManyToManyBidirectionalListVsSet\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | private static Map<String, Object> convertClaimsIfNecessary(Map<String, Object> claims) {
Map<String, Object> convertedClaims = new HashMap<>(claims);
Object value = claims.get(OAuth2TokenIntrospectionClaimNames.ISS);
if (value != null && !(value instanceof URL)) {
URL convertedValue = ClaimConversionService.getSharedInstance().convert(value, URL.class);
if (convertedValue != null) {
convertedClaims.put(OAuth2TokenIntrospectionClaimNames.ISS, convertedValue);
}
}
value = claims.get(OAuth2TokenIntrospectionClaimNames.SCOPE);
if (value != null && !(value instanceof List)) {
Object convertedValue = ClaimConversionService.getSharedInstance()
.convert(value, OBJECT_TYPE_DESCRIPTOR, LIST_STRING_TYPE_DESCRIPTOR);
if (convertedValue != null) {
convertedClaims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, convertedValue);
} | }
value = claims.get(OAuth2TokenIntrospectionClaimNames.AUD);
if (value != null && !(value instanceof List)) {
Object convertedValue = ClaimConversionService.getSharedInstance()
.convert(value, OBJECT_TYPE_DESCRIPTOR, LIST_STRING_TYPE_DESCRIPTOR);
if (convertedValue != null) {
convertedClaims.put(OAuth2TokenIntrospectionClaimNames.AUD, convertedValue);
}
}
return convertedClaims;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2TokenIntrospectionAuthenticationProvider.java | 1 |
请完成以下Java代码 | public ElementPermission getPermission(final int elementId)
{
final ElementResource resource = elementResource(elementId);
final ElementPermission permission = getPermissionOrDefault(resource);
return permission != null ? permission : ElementPermission.none(resource);
}
public ElementResource elementResource(final int elementId)
{
return ElementResource.of(elementTableName, elementId);
}
public ElementPermission noPermissions(final int elementId)
{
return ElementPermission.none(elementResource(elementId));
}
public static class Builder extends PermissionsBuilder<ElementPermission, ElementPermissions>
{
private String elementTableName;
@Override
protected ElementPermissions createPermissionsInstance()
{
return new ElementPermissions(this);
} | public Builder setElementTableName(final String elementTableName)
{
this.elementTableName = elementTableName;
return this;
}
public String getElementTableName()
{
Check.assumeNotEmpty(elementTableName, "elementTableName not empty");
return elementTableName;
}
@Override
protected void assertValidPermissionToAdd(final ElementPermission permission)
{
final String elementTableName = getElementTableName();
if (!Objects.equals(elementTableName, permission.getResource().getElementTableName()))
{
throw new IllegalArgumentException("Permission to add " + permission + " is not matching element table name '" + elementTableName + "'");
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ElementPermissions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Employee {
//
private long id;
private String firstName;
private String lastName;
private String emailId;
public Employee() {
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "first_name", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
} | public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name = "email_address", nullable = false)
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", emailId='" + emailId + '\'' +
'}';
}
} | repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSources\SpringRestAPI\src\main\java\spring\boot\model\Employee.java | 2 |
请完成以下Java代码 | public String getLocalName() {
return name;
}
public AttributeDefinition getDefinition() {
return definition;
}
public AttributeDefinition getDefinition(final String name) {
return definitions.get(name);
}
private static final Map<String, Element> MAP;
static {
final Map<String, Element> map = new HashMap<String, Element>();
for (Element element : values()) {
final String name = element.getLocalName(); | if (name != null)
map.put(name, element);
}
MAP = map;
}
public static Element forName(String localName) {
final Element element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
@SuppressWarnings("unused")
private static List<AttributeDefinition> getAttributeDefinitions(final AttributeDefinition... attributeDefinitions) {
return Arrays.asList(attributeDefinitions);
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\Element.java | 1 |
请完成以下Java代码 | protected void channelRead0(ChannelHandlerContext ctx, Operation msg) throws Exception {
Long result = calculateEndpoint(msg);
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED), result.toString());
ctx.fireChannelRead(result);
}
private long calculateEndpoint(Operation operation) {
String operator = operation.getOperator().toLowerCase().trim();
switch (operator) {
case "add":
return operation.getNumber1() + operation.getNumber2();
case "multiply":
return operation.getNumber1() * operation.getNumber2();
default:
throw new IllegalArgumentException("Operation not defined");
}
}
public static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpResponse res, String content) { | // Generate an error page if response getStatus code is not OK (200).
ByteBuf buf = Unpooled.copiedBuffer(content, CharsetUtil.UTF_8);
res.content().writeBytes(buf);
HttpUtil.setContentLength(res, res.content().readableBytes());
ctx.channel().writeAndFlush(res);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR), "Operation not defined");
ctx.fireExceptionCaught(cause);
}
} | repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\netty\CalculatorOperationHandler.java | 1 |
请完成以下Java代码 | public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Resource Assignment.
@param S_ResourceAssignment_ID
Resource Assignment
*/
public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{
if (S_ResourceAssignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID));
}
/** Get Resource Assignment.
@return Resource Assignment
*/
public int getS_ResourceAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_S_Resource getS_Resource() throws RuntimeException
{
return (I_S_Resource)MTable.get(getCtx(), I_S_Resource.Table_Name)
.getPO(getS_Resource_ID(), get_TrxName()); }
/** Set Resource.
@param S_Resource_ID
Resource
*/
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else | set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
/** Get Resource.
@return Resource
*/
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getS_Resource_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ResourceAssignment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static TaxProductIdProvider getTaxProductIdProvider(@NonNull final JsonExternalSystemRequest externalSystemRequest)
{
final ImmutableMap.Builder<JsonMetasfreshId, List<BigDecimal>> productId2VatRatesBuilder = ImmutableMap.builder();
final Map<String, String> parameters = externalSystemRequest.getParameters();
final String normalVatRates = parameters.get(PARAM_NORMAL_VAT_RATES);
final String normalVatProductId = parameters.get(PARAM_FREIGHT_COST_NORMAL_PRODUCT_ID);
if (Check.isNotBlank(normalVatProductId) && Check.isNotBlank(normalVatRates))
{
final List<BigDecimal> rates = NumberUtils.asBigDecimalList(normalVatRates, ",");
final JsonMetasfreshId productId = JsonMetasfreshId.of(Integer.parseInt(normalVatProductId));
productId2VatRatesBuilder.put(productId, rates);
}
final String reducedVatRates = parameters.get(PARAM_REDUCED_VAT_RATES);
final String reducedVatProductId = parameters.get(PARAM_FREIGHT_COST_REDUCED_PRODUCT_ID);
if (Check.isNotBlank(reducedVatProductId) && Check.isNotBlank(reducedVatRates))
{
final List<BigDecimal> rates = NumberUtils.asBigDecimalList(reducedVatRates, ",");
final JsonMetasfreshId productId = JsonMetasfreshId.of(Integer.parseInt(reducedVatProductId));
productId2VatRatesBuilder.put(productId, rates);
}
final ImmutableMap<JsonMetasfreshId, List<BigDecimal>> productId2VatRates = productId2VatRatesBuilder.build();
if (productId2VatRates.isEmpty())
{
return null;
}
return TaxProductIdProvider.of(productId2VatRates);
}
@NonNull
private CurrencyInfoProvider getCurrencyInfoProvider(@NonNull final String basePath, @NonNull final String clientId, @NonNull final String clientSecret)
{
final GetCurrenciesRequest getCurrenciesRequest = GetCurrenciesRequest.builder()
.baseUrl(basePath)
.clientId(clientId) | .clientSecret(clientSecret)
.build();
return (CurrencyInfoProvider)producerTemplate
.sendBody("direct:" + GET_CURRENCY_ROUTE_ID, ExchangePattern.InOut, getCurrenciesRequest);
}
@NonNull
private SalutationInfoProvider getSalutationInfoProvider(@NonNull final String basePath, @NonNull final String clientId, @NonNull final String clientSecret)
{
final GetSalutationsRequest getSalutationsRequest = GetSalutationsRequest.builder()
.baseUrl(basePath)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
return (SalutationInfoProvider)producerTemplate
.sendBody("direct:" + GET_SALUTATION_ROUTE_ID, ExchangePattern.InOut, getSalutationsRequest);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\order\processor\BuildOrdersContextProcessor.java | 2 |
请完成以下Java代码 | public Set<Attribute> getByIds(@NonNull final Collection<AttributeId> ids)
{
if (ids.isEmpty()) {return ImmutableSet.of();}
return ids.stream()
.distinct()
.map(this::getById)
.collect(ImmutableSet.toImmutableSet());
}
@NonNull
public AttributeId getIdByCode(@NonNull final AttributeCode attributeCode)
{
return getByCode(attributeCode).getAttributeId();
}
public Set<Attribute> getByCodes(final Set<AttributeCode> attributeCodes)
{
if (attributeCodes.isEmpty()) {return ImmutableSet.of();}
return attributeCodes.stream()
.distinct()
.map(this::getByCode)
.collect(ImmutableSet.toImmutableSet());
}
@NonNull
public ImmutableList<AttributeCode> getOrderedAttributeCodesByIds(@NonNull final List<AttributeId> orderedAttributeIds)
{
if (orderedAttributeIds.isEmpty())
{
return ImmutableList.of(); | }
return orderedAttributeIds.stream()
.map(this::getById)
.filter(Attribute::isActive)
.map(Attribute::getAttributeCode)
.collect(ImmutableList.toImmutableList());
}
public Stream<Attribute> streamActive()
{
return attributesById.values().stream().filter(Attribute::isActive);
}
public boolean isActiveAttribute(final AttributeId id)
{
final Attribute attribute = getByIdOrNull(id);
return attribute != null && attribute.isActive();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributesMap.java | 1 |
请完成以下Java代码 | public class WEBUI_M_ReceiptSchedule_ReceiveCUs_WithParam extends WEBUI_M_ReceiptSchedule_ReceiveCUs implements IProcessDefaultParametersProvider
{
private static final String PARAM_QtyCUsPerTU = "QtyCUsPerTU";
@Param(parameterName = PARAM_QtyCUsPerTU, mandatory = true)
private BigDecimal p_QtyCUsPerTU;
public WEBUI_M_ReceiptSchedule_ReceiveCUs_WithParam()
{
super();
// configure defaults
setAllowMultipleReceiptsSchedules(false);
setAllowNoQuantityAvailable(true);
}
@Override
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_QtyCUsPerTU.equals(parameter.getColumnName()))
{
final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule();
return getDefaultAvailableQtyToReceive(receiptSchedule);
}
else
{
return DEFAULT_VALUE_NOTAVAILABLE;
}
}
@Override | protected Stream<I_M_ReceiptSchedule> streamReceiptSchedulesToReceive()
{
return Stream.of(getM_ReceiptSchedule());
}
private I_M_ReceiptSchedule getM_ReceiptSchedule()
{
return getRecord(I_M_ReceiptSchedule.class);
}
@Override
protected BigDecimal getEffectiveQtyToReceive(I_M_ReceiptSchedule rs)
{
if(p_QtyCUsPerTU == null || p_QtyCUsPerTU.signum() <= 0)
{
throw new FillMandatoryException(PARAM_QtyCUsPerTU);
}
return p_QtyCUsPerTU;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveCUs_WithParam.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Link" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"link"
})
public static class LinkAttachment {
@XmlElement(name = "Name")
protected String name;
@XmlElement(name = "Link", required = true)
protected String link;
/**
* Gets the value of the name property. | *
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the link property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLink() {
return link;
}
/**
* Sets the value of the link property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLink(String value) {
this.link = value;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AttachmentsType.java | 2 |
请完成以下Java代码 | public static void writeClassToDisk(String proxyClassName, Class aClass) {
String path = ".\\" + proxyClassName + ".class";
writeClassToDisk(path, proxyClassName, aClass);
}
/**
* @param path 输出路径
* @param proxyClassName 代理类名称($proxy4)
* @param aClass 目标类对象
*/
public static void writeClassToDisk(String path, String proxyClassName, Class aClass) {
byte[] classFile = ProxyGenerator.generateProxyClass(proxyClassName, new Class[]{aClass});
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
fos.write(classFile); | fos.flush();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
} | repos\spring-boot-student-master\spring-boot-student-mybatis\src\main\java\com\xiaolyuh\mybatis\JdkProxySourceClassUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class KeyValue
{
@NonNull String targetTableColumnName;
@NonNull String selectionTableColumnName;
@NonNull FTSJoinColumn.ValueType valueType;
@Nullable Object value;
public static KeyValue ofJoinColumnAndValue(
@NonNull final FTSJoinColumn joinColumn,
@Nullable final Object value)
{
return builder()
.targetTableColumnName(joinColumn.getTargetTableColumnName())
.selectionTableColumnName(joinColumn.getSelectionTableColumnName())
.valueType(joinColumn.getValueType())
.value(value)
.build();
}
}
@EqualsAndHashCode
@ToString
public static class KeyValueMap
{
private final ImmutableMap<String, KeyValue> keysBySelectionTableColumnName;
public KeyValueMap(@NonNull final List<KeyValue> keys) | {
if (keys.isEmpty())
{
throw new AdempiereException("empty key not allowed");
}
keysBySelectionTableColumnName = Maps.uniqueIndex(keys, KeyValue::getSelectionTableColumnName);
}
@Nullable
public Object getValueBySelectionTableColumnName(final String selectionTableColumName)
{
final KeyValue keyValue = keysBySelectionTableColumnName.get(selectionTableColumName);
return keyValue != null ? keyValue.getValue() : null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\FTSSearchResultItem.java | 2 |
请完成以下Java代码 | public String getProcessDefinitionName() {
return processDefinitionName;
}
public String getProcessDefinitionCategory() {
return processDefinitionCategory;
}
public Integer getProcessDefinitionVersion() {
return processDefinitionVersion;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public String getStartedBy() {
return startedBy;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public boolean isExcludeSubprocesses() {
return excludeSubprocesses;
}
public List<String> getProcessKeyNotIn() {
return processKeyNotIn;
}
public Date getStartedAfter() {
return startedAfter;
}
public Date getStartedBefore() {
return startedBefore;
}
public Date getFinishedAfter() {
return finishedAfter;
}
public Date getFinishedBefore() {
return finishedBefore;
}
public String getInvolvedUser() {
return involvedUser;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
} | public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public boolean isDeleted() {
return deleted;
}
public boolean isNotDeleted() {
return notDeleted;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean isWithException() {
return withJobException;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public List<String> getInvolvedGroups() {
return involvedGroups;
}
public HistoricProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) {
if (involvedGroups == null || involvedGroups.isEmpty()) {
throw new ActivitiIllegalArgumentException("Involved groups list is null or empty.");
}
if (inOrStatement) {
this.currentOrQueryObject.involvedGroups = involvedGroups;
} else {
this.involvedGroups = involvedGroups;
}
return this;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void onBlurEvent() {
outputText = inputText.toUpperCase();
}
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 getComponentSuite() {
return componentSuite;
}
public void setComponentSuite(String componentSuite) {
this.componentSuite = componentSuite;
}
public List<Technology> getTechnologies() {
return technologies;
}
public void setTechnologies(List<Technology> technologies) {
this.technologies = technologies;
}
public String getInputText() {
return inputText;
}
public void setInputText(String inputText) {
this.inputText = inputText;
}
public String getOutputText() {
return outputText;
} | public void setOutputText(String outputText) {
this.outputText = outputText;
}
public class Technology {
private String name;
private String currentVersion;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCurrentVersion() {
return currentVersion;
}
public void setCurrentVersion(String currentVersion) {
this.currentVersion = currentVersion;
}
}
} | repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\HelloPFBean.java | 2 |
请完成以下Java代码 | private Collection<ApplicationContextInitializer<?>> getInitializers() {
List<ApplicationContextInitializer<?>> initializers = new ArrayList<>();
initializers.add(new RestartScopeInitializer());
return initializers;
}
private Collection<ApplicationListener<?>> getListeners() {
List<ApplicationListener<?>> listeners = new ArrayList<>();
listeners.add(new AnsiOutputApplicationListener());
listeners.add(EnvironmentPostProcessorApplicationListener
.with(EnvironmentPostProcessorsFactory.of(ConfigDataEnvironmentPostProcessor.class)));
listeners.add(new LoggingApplicationListener());
listeners.add(new RemoteUrlPropertyExtractor());
return listeners;
}
private Banner getBanner() {
ClassPathResource banner = new ClassPathResource("remote-banner.txt", RemoteSpringApplication.class);
return new ResourceBanner(banner);
}
private void waitIndefinitely() {
while (true) {
try {
Thread.sleep(1000);
} | catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
/**
* Run the {@link RemoteSpringApplication}.
* @param args the program arguments (including the remote URL as a non-option
* argument)
*/
public static void main(String[] args) {
new RemoteSpringApplication().run(args);
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\RemoteSpringApplication.java | 1 |
请完成以下Java代码 | public int getC_ElementValue_ID()
{
return get_ValueAsInt(COLUMNNAME_C_ElementValue_ID);
}
@Override
public void setC_Invoice_Acct_ID (final int C_Invoice_Acct_ID)
{
if (C_Invoice_Acct_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Acct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_Acct_ID, C_Invoice_Acct_ID);
}
@Override
public int getC_Invoice_Acct_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_Acct_ID);
}
@Override
public org.compiere.model.I_C_Invoice getC_Invoice()
{
return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class);
}
@Override
public void setC_Invoice(final org.compiere.model.I_C_Invoice C_Invoice)
{
set_ValueFromPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class, C_Invoice);
}
@Override
public void setC_Invoice_ID (final int C_Invoice_ID)
{
if (C_Invoice_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, C_Invoice_ID);
}
@Override
public int getC_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_ID);
} | @Override
public org.compiere.model.I_C_InvoiceLine getC_InvoiceLine()
{
return get_ValueAsPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class);
}
@Override
public void setC_InvoiceLine(final org.compiere.model.I_C_InvoiceLine C_InvoiceLine)
{
set_ValueFromPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class, C_InvoiceLine);
}
@Override
public void setC_InvoiceLine_ID (final int C_InvoiceLine_ID)
{
if (C_InvoiceLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, C_InvoiceLine_ID);
}
@Override
public int getC_InvoiceLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_InvoiceLine_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional
public void createAuthors() throws IOException {
Author mt = new Author();
mt.setId(1L);
mt.setName("Martin Ticher");
mt.setAge(43);
mt.setGenre("Horror");
mt.setAvatar(Files.readAllBytes(new File("avatars/mt.png").toPath()));
Author cd = new Author();
cd.setId(2L);
cd.setName("Carla Donnoti");
cd.setAge(31);
cd.setGenre("Science Fiction");
cd.setAvatar(Files.readAllBytes(new File("avatars/cd.png").toPath()));
Author re = new Author();
re.setId(3L);
re.setName("Rennata Elibol");
re.setAge(46);
re.setGenre("Fantasy");
re.setAvatar(Files.readAllBytes(new File("avatars/re.png").toPath()));
authorRepository.save(mt);
authorRepository.save(cd);
authorRepository.save(re);
} | public List<Author> fetchAuthorsByAgeGreaterThanEqual(int age) {
List<Author> authors = authorRepository.findByAgeGreaterThanEqual(age);
return authors;
}
@Transactional(readOnly = true)
public byte[] fetchAuthorAvatarViaId(long id) {
Author author = authorRepository.findById(id).orElseThrow();
return author.getAvatar();
}
@Transactional(readOnly = true)
public List<Author> fetchAuthorsDetailsByAgeGreaterThanEqual(int age) {
List<Author> authors = authorRepository.findByAgeGreaterThanEqual(40);
// don't do this since this is a N+1 case
authors.forEach(a -> {
a.getAvatar();
});
return authors;
}
@Transactional(readOnly = true)
public List<AuthorDto> fetchAuthorsWithAvatarsByAgeGreaterThanEqual(int age) {
List<AuthorDto> authors = authorRepository.findDtoByAgeGreaterThanEqual(40);
return authors;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootAttributeLazyLoadingBasic\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public int getRef_RMA_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_RMA_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Vertriebsbeauftragter.
@param SalesRep_ID | Sales Representative or Company Agent
*/
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Vertriebsbeauftragter.
@return Sales Representative or Company Agent
*/
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RMA.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Pet extends NamedEntity {
@Column
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate birthDate;
@ManyToOne
@JoinColumn(name = "type_id")
private PetType type;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "pet_id")
@OrderBy("date ASC")
private final Set<Visit> visits = new LinkedHashSet<>();
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public LocalDate getBirthDate() { | return this.birthDate;
}
public PetType getType() {
return this.type;
}
public void setType(PetType type) {
this.type = type;
}
public Collection<Visit> getVisits() {
return this.visits;
}
public void addVisit(Visit visit) {
getVisits().add(visit);
}
} | repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\Pet.java | 2 |
请完成以下Java代码 | private static WorkflowLauncher toWorkflowLauncher(final InventoryJobReference jobRef)
{
final WorkflowLauncherBuilder builder = WorkflowLauncher.builder()
.applicationId(APPLICATION_ID)
.caption(computeCaption(jobRef));
if (jobRef.isJobStarted())
{
final WFProcessId wfProcessId = toWFProcessId(jobRef.getInventoryId());
return builder.startedWFProcessId(wfProcessId).build();
}
else
{
return builder.wfParameters(InventoryWFProcessStartParams.of(jobRef).toParams()).build();
}
}
private static @NonNull WorkflowLauncherCaption computeCaption(final InventoryJobReference jobRef)
{
return WorkflowLauncherCaption.of(
TranslatableStrings.builder()
.append(jobRef.getWarehouseName()) | .append(" | ")
.appendDate(jobRef.getMovementDate())
.append(" | ")
.append(jobRef.getDocumentNo())
.build()
);
}
public QueryLimit getLaunchersLimit()
{
final int limitInt = sysConfigBL.getIntValue(Constants.SYSCONFIG_LaunchersLimit, -100);
return limitInt == -100
? Constants.DEFAULT_LaunchersLimit
: QueryLimit.ofInt(limitInt);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\launchers\InventoryWorkflowLaunchersProvider.java | 1 |
请完成以下Java代码 | public File createPDF ()
{
try
{
File temp = File.createTempFile(get_TableName()+get_ID()+"_", ".pdf");
return createPDF (temp);
}
catch (Exception e)
{
log.error("Could not create PDF - " + e.getMessage());
}
return null;
} // getPDF
/**
* Create PDF file
* @param file output file
* @return file if success
*/
public File createPDF (File file)
{
// ReportEngine re = ReportEngine.get (getCtx(), ReportEngine.INVOICE, getC_Invoice_ID());
// if (re == null)
return null;
// return re.getPDF(file);
} // createPDF
/**
* Get Process Message
* @return clear text error message
*/
@Override
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/** | * Get Document Owner (Responsible)
* @return AD_User_ID (Created By)
*/
@Override
public int getDoc_User_ID()
{
return getCreatedBy();
} // getDoc_User_ID
/**
* Get Document Approval Amount
* @return DR amount
*/
@Override
public BigDecimal getApprovalAmt()
{
return getTotalDr();
} // getApprovalAmt
} // MJournalBatch | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournalBatch.java | 1 |
请完成以下Java代码 | static DocumentId convertInvoiceIdToDocumentId(@NonNull final InvoiceId invoiceId)
{
return DocumentId.of(invoiceId);
}
static InvoiceId convertDocumentIdToInvoiceId(@NonNull final DocumentId rowId)
{
return rowId.toId(InvoiceId::ofRepoId);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(values.get(this))
.toString();
}
@Override
public DocumentId getId()
{
return rowId;
}
public ClientAndOrgId getClientAndOrgId()
{
return clientAndOrgId;
}
@Override
public boolean isProcessed()
{
return false;
}
@Override
public DocumentPath getDocumentPath()
{
return null;
} | @Override
public Set<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
@Override
public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName()
{
return values.getViewEditorRenderModeByFieldName();
}
public BPartnerId getBPartnerId()
{
return bpartner.getIdAs(BPartnerId::ofRepoId);
}
public InvoiceRow withPreparedForAllocationSet() { return withPreparedForAllocation(true); }
public InvoiceRow withPreparedForAllocationUnset() { return withPreparedForAllocation(false); }
public InvoiceRow withPreparedForAllocation(final boolean isPreparedForAllocation)
{
return this.isPreparedForAllocation != isPreparedForAllocation
? toBuilder().isPreparedForAllocation(isPreparedForAllocation).build()
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRow.java | 1 |
请完成以下Java代码 | public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getDeleteReason() {
return deleteReason;
}
public String getOwner() {
return owner;
}
public String getAssignee() {
return assignee;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Long getDuration() {
return duration;
}
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public int getPriority() {
return priority;
}
public Date getDue() {
return due;
}
public String getParentTaskId() {
return parentTaskId;
}
public Date getFollowUp() {
return followUp;
}
public String getTenantId() {
return tenantId;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
/**
* Returns task State of history tasks
*/ | public String getTaskState() { return taskState; }
public static HistoricTaskInstanceDto fromHistoricTaskInstance(HistoricTaskInstance taskInstance) {
HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto();
dto.id = taskInstance.getId();
dto.processDefinitionKey = taskInstance.getProcessDefinitionKey();
dto.processDefinitionId = taskInstance.getProcessDefinitionId();
dto.processInstanceId = taskInstance.getProcessInstanceId();
dto.executionId = taskInstance.getExecutionId();
dto.caseDefinitionKey = taskInstance.getCaseDefinitionKey();
dto.caseDefinitionId = taskInstance.getCaseDefinitionId();
dto.caseInstanceId = taskInstance.getCaseInstanceId();
dto.caseExecutionId = taskInstance.getCaseExecutionId();
dto.activityInstanceId = taskInstance.getActivityInstanceId();
dto.name = taskInstance.getName();
dto.description = taskInstance.getDescription();
dto.deleteReason = taskInstance.getDeleteReason();
dto.owner = taskInstance.getOwner();
dto.assignee = taskInstance.getAssignee();
dto.startTime = taskInstance.getStartTime();
dto.endTime = taskInstance.getEndTime();
dto.duration = taskInstance.getDurationInMillis();
dto.taskDefinitionKey = taskInstance.getTaskDefinitionKey();
dto.priority = taskInstance.getPriority();
dto.due = taskInstance.getDueDate();
dto.parentTaskId = taskInstance.getParentTaskId();
dto.followUp = taskInstance.getFollowUpDate();
dto.tenantId = taskInstance.getTenantId();
dto.removalTime = taskInstance.getRemovalTime();
dto.rootProcessInstanceId = taskInstance.getRootProcessInstanceId();
dto.taskState = taskInstance.getTaskState();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("VariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", type=").append(type != null ? type.getTypeName() : "null");
if (executionId != null) {
sb.append(", executionId=").append(executionId);
}
if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
if (processDefinitionId != null) {
sb.append(", processDefinitionId=").append(processDefinitionId);
}
if (scopeId != null) {
sb.append(", scopeId=").append(scopeId);
}
if (subScopeId != null) {
sb.append(", subScopeId=").append(subScopeId);
}
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (scopeDefinitionId != null) {
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (longValue != null) { | sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\VariableInstanceEntityImpl.java | 2 |
请完成以下Java代码 | public JsonNode waitForReply() {
try {
if (reply.await(requestTimeoutMs, TimeUnit.MILLISECONDS)) {
log.trace("Waited for reply");
List<JsonNode> lastMsgs = getLastMsgs();
return lastMsgs.isEmpty() ? null : lastMsgs.get(0);
}
} catch (InterruptedException e) {
log.debug("Failed to await reply", e);
}
log.trace("No reply arrived within {} ms", requestTimeoutMs);
throw new IllegalStateException("No WS reply arrived within " + requestTimeoutMs + " ms");
}
private List<JsonNode> getLastMsgs() {
if (lastMsgs.isEmpty()) {
return lastMsgs;
}
List<JsonNode> errors = lastMsgs.stream()
.map(msg -> msg.get("errorMsg"))
.filter(errorMsg -> errorMsg != null && !errorMsg.isNull() && StringUtils.isNotEmpty(errorMsg.asText()))
.toList();
if (!errors.isEmpty()) {
throw new RuntimeException("WS error from server: " + errors.stream()
.map(JsonNode::asText)
.collect(Collectors.joining(", ")));
}
return lastMsgs;
} | public Map<String, String> getLatest(UUID deviceId) {
Map<String, String> updates = new HashMap<>();
getLastMsgs().forEach(msg -> {
EntityDataUpdate update = JacksonUtil.treeToValue(msg, EntityDataUpdate.class);
Map<String, String> latest = update.getLatest(deviceId);
updates.putAll(latest);
});
return updates;
}
@Override
protected void onSetSSLParameters(SSLParameters sslParameters) {
sslParameters.setEndpointIdentificationAlgorithm(null);
}
} | repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\client\WsClient.java | 1 |
请完成以下Java代码 | public String getType() {
return type;
}
public BatchQuery tenantIdIn(String... tenantIds) {
ensureNotNull("tenantIds", (Object[]) tenantIds);
this.tenantIds = tenantIds;
isTenantIdSet = true;
return this;
}
public String[] getTenantIds() {
return tenantIds;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public BatchQuery withoutTenantId() {
this.tenantIds = null;
isTenantIdSet = true;
return this;
}
public BatchQuery active() {
this.suspensionState = SuspensionState.ACTIVE;
return this;
}
public BatchQuery suspended() {
this.suspensionState = SuspensionState.SUSPENDED;
return this;
}
public SuspensionState getSuspensionState() {
return suspensionState;
} | public BatchQuery orderById() {
return orderBy(BatchQueryProperty.ID);
}
@Override
public BatchQuery orderByTenantId() {
return orderBy(BatchQueryProperty.TENANT_ID);
}
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getBatchManager()
.findBatchCountByQueryCriteria(this);
}
public List<Batch> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getBatchManager()
.findBatchesByQueryCriteria(this, page);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchQueryImpl.java | 1 |
请完成以下Java代码 | public String getProductValue(@NonNull final ProductId productId)
{
return productsService.getProductValue(productId);
}
// TODO move this method to de.metas.bpartner.service.IBPartnerDAO since it has nothing to do with price list
// TODO: IdentifierString must also be moved to the module containing IBPartnerDAO
public Optional<BPartnerId> getBPartnerId(final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final BPartnerQuery query = createBPartnerQuery(bpartnerIdentifier, orgId);
return bpartnersRepo.retrieveBPartnerIdBy(query);
}
private static BPartnerQuery createBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final Type type = bpartnerIdentifier.getType();
final BPartnerQuery.BPartnerQueryBuilder builder = BPartnerQuery.builder();
if (orgId != null)
{
builder.onlyOrgId(orgId);
}
if (Type.METASFRESH_ID.equals(type))
{
return builder
.bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId))
.build();
}
else if (Type.EXTERNAL_ID.equals(type))
{ | return builder
.externalId(bpartnerIdentifier.asExternalId())
.build();
}
else if (Type.VALUE.equals(type))
{
return builder
.bpartnerValue(bpartnerIdentifier.asValue())
.build();
}
else if (Type.GLN.equals(type))
{
return builder
.gln(bpartnerIdentifier.asGLN())
.build();
}
else
{
throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_pricelist\BpartnerPriceListServicesFacade.java | 1 |
请完成以下Java代码 | public void startNested(RequestPredicate predicate) {
}
@Override
public void endNested(RequestPredicate predicate) {
}
@Override
public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) {
DispatcherHandlerMappingDetails details = new DispatcherHandlerMappingDetails();
details.setHandlerFunction(new HandlerFunctionDescription(handlerFunction));
this.descriptions.add(
new DispatcherHandlerMappingDescription(predicate.toString(), handlerFunction.toString(), details));
}
@Override
public void resources(Function<ServerRequest, Mono<Resource>> lookupFunction) {
}
@Override
public void attributes(Map<String, Object> attributes) {
}
@Override | public void unknown(RouterFunction<?> routerFunction) {
}
}
static class DispatcherHandlersMappingDescriptionProviderRuntimeHints implements RuntimeHintsRegistrar {
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.bindingRegistrar.registerReflectionHints(hints.reflection(),
DispatcherHandlerMappingDescription.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\mappings\DispatcherHandlersMappingDescriptionProvider.java | 1 |
请完成以下Java代码 | public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Human other = (Human) obj;
if (age != other.age) {
return false;
}
if (name == null) {
if (other.name != null) {
return false; | }
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Human [name=").append(name).append(", age=").append(age).append("]");
return builder.toString();
}
} | repos\tutorials-master\core-java-modules\core-java-lambdas\src\main\java\com\baeldung\java8\entity\Human.java | 1 |
请完成以下Java代码 | public Config setLayer1Size(int layer1Size)
{
this.layer1Size = layer1Size;
return this;
}
public int getLayer1Size()
{
return layer1Size;
}
public Config setNumThreads(int numThreads)
{
this.numThreads = numThreads;
return this;
}
public int getNumThreads()
{
return numThreads;
}
public Config setUseHierarchicalSoftmax(boolean hs)
{
this.hs = hs;
return this;
}
public boolean useHierarchicalSoftmax()
{
return hs;
}
public Config setUseContinuousBagOfWords(boolean cbow)
{
this.cbow = cbow;
return this;
}
public boolean useContinuousBagOfWords()
{
return cbow;
}
public Config setSample(float sample)
{
this.sample = sample;
return this;
}
public float getSample()
{
return sample;
}
public Config setAlpha(float alpha) | {
this.alpha = alpha;
return this;
}
public float getAlpha()
{
return alpha;
}
public Config setInputFile(String inputFile)
{
this.inputFile = inputFile;
return this;
}
public String getInputFile()
{
return inputFile;
}
public TrainingCallback getCallback()
{
return callback;
}
public void setCallback(TrainingCallback callback)
{
this.callback = callback;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Config.java | 1 |
请完成以下Java代码 | public void setC_Campaign_ID (int C_Campaign_ID)
{
if (C_Campaign_ID < 1)
set_Value (COLUMNNAME_C_Campaign_ID, null);
else
set_Value (COLUMNNAME_C_Campaign_ID, Integer.valueOf(C_Campaign_ID));
}
/** Get Campaign.
@return Marketing Campaign
*/
public int getC_Campaign_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Campaign_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Promotion.
@param M_Promotion_ID Promotion */
public void setM_Promotion_ID (int M_Promotion_ID)
{
if (M_Promotion_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, Integer.valueOf(M_Promotion_ID));
}
/** Get Promotion.
@return Promotion */
public int getM_Promotion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Promotion_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName () | {
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Relative Priority.
@param PromotionPriority
Which promotion should be apply to a product
*/
public void setPromotionPriority (int PromotionPriority)
{
set_Value (COLUMNNAME_PromotionPriority, Integer.valueOf(PromotionPriority));
}
/** Get Relative Priority.
@return Which promotion should be apply to a product
*/
public int getPromotionPriority ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionPriority);
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_M_Promotion.java | 1 |
请完成以下Java代码 | public ProcessDefinition getProcessDefinition() {
return processDefinition;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public String getTransitionName() {
return transitionName;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public BusinessProcessEventType getType() {
return type;
} | @Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public String toString() {
return "Event '" + processDefinition.getKey() + "' ['" + type + "', " + (type == BusinessProcessEventType.TAKE ? transitionName : activityId) + "]";
}
@Override
public VariableScope getVariableScope() {
return variableScope;
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\event\CdiBusinessProcessEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private JsonRemittanceAdviceLine extractLineInfo(@NonNull final ListLineItemType lineItemType)
{
final Supplier<RuntimeException> missingMandatoryDataExSupplier =
() -> new RuntimeException("Missing mandatory data! ListLineItemType: " + lineItemType);
if (lineItemType.getListLineItemExtension() == null
|| lineItemType.getListLineItemExtension().getListLineItemExtension() == null)
{
throw missingMandatoryDataExSupplier.get();
}
final REMADVListLineItemExtensionType remadvLineItemExtension = lineItemType.getListLineItemExtension().getListLineItemExtension().getREMADVListLineItemExtension();
if (remadvLineItemExtension == null)
{
throw missingMandatoryDataExSupplier.get();
}
return JsonRemittanceAdviceLineProducer.of(lineItemType.getPositionNumber(), remadvLineItemExtension).getLine();
}
@Nullable | private String extractSendDateOrNull(@NonNull final ErpelMessageType erpelMessageType)
{
if (erpelMessageType.getErpelBusinessDocumentHeader() == null)
{
return null;
}
final DateTimeType sendDate = erpelMessageType.getErpelBusinessDocumentHeader().getInterchangeHeader().getDateTime();
final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(sendDate.getDate() + " " + sendDate.getTime(), dateTimeFormatter)
.atZone(ZoneId.of(DOCUMENT_ZONE_ID))
.toInstant()
.toString();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\remadvimport\ecosio\RemadvXmlToJsonProcessor.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAvailableInAPI (final boolean AvailableInAPI)
{
set_Value (COLUMNNAME_AvailableInAPI, AvailableInAPI);
}
@Override
public boolean isAvailableInAPI()
{
return get_ValueAsBoolean(COLUMNNAME_AvailableInAPI);
}
@Override
public void setDataEntry_Section_ID (final int DataEntry_Section_ID)
{
if (DataEntry_Section_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, DataEntry_Section_ID);
}
@Override
public int getDataEntry_Section_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_Section_ID);
}
@Override
public de.metas.dataentry.model.I_DataEntry_SubTab getDataEntry_SubTab()
{
return get_ValueAsPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class);
}
@Override
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代码 | private List<Resource> resolveSchemaResources(ResourcePatternResolver resolver, String pattern) {
try {
return Arrays.asList(resolver.getResources(pattern));
}
catch (IOException ex) {
logger.debug(LogMessage.format("Could not resolve schema location: '%s'", pattern), ex);
return Collections.emptyList();
}
}
@Bean
@ConditionalOnMissingBean
BatchLoaderRegistry batchLoaderRegistry() {
return new DefaultBatchLoaderRegistry();
}
@Bean
@ConditionalOnMissingBean
ExecutionGraphQlService executionGraphQlService(GraphQlSource graphQlSource,
BatchLoaderRegistry batchLoaderRegistry) {
DefaultExecutionGraphQlService service = new DefaultExecutionGraphQlService(graphQlSource);
service.addDataLoaderRegistrar(batchLoaderRegistry);
return service;
}
@Bean
@ConditionalOnMissingBean
AnnotatedControllerConfigurer annotatedControllerConfigurer(
@Qualifier(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME) ObjectProvider<Executor> executorProvider,
ObjectProvider<HandlerMethodArgumentResolver> argumentResolvers) {
AnnotatedControllerConfigurer controllerConfigurer = new AnnotatedControllerConfigurer();
controllerConfigurer
.configureBinder((options) -> options.conversionService(ApplicationConversionService.getSharedInstance()));
executorProvider.ifAvailable(controllerConfigurer::setExecutor);
argumentResolvers.orderedStream().forEach(controllerConfigurer::addCustomArgumentResolver);
return controllerConfigurer;
}
@Bean
DataFetcherExceptionResolver annotatedControllerConfigurerDataFetcherExceptionResolver(
AnnotatedControllerConfigurer annotatedControllerConfigurer) {
return annotatedControllerConfigurer.getExceptionResolver();
}
@ConditionalOnClass(ScrollPosition.class)
@Configuration(proxyBeanMethods = false)
static class GraphQlDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean
EncodingCursorStrategy<ScrollPosition> cursorStrategy() {
return CursorStrategy.withEncoder(new ScrollPositionCursorStrategy(), CursorEncoder.base64());
} | @Bean
@SuppressWarnings("unchecked")
GraphQlSourceBuilderCustomizer cursorStrategyCustomizer(CursorStrategy<?> cursorStrategy) {
if (cursorStrategy.supports(ScrollPosition.class)) {
CursorStrategy<ScrollPosition> scrollCursorStrategy = (CursorStrategy<ScrollPosition>) cursorStrategy;
ConnectionFieldTypeVisitor connectionFieldTypeVisitor = ConnectionFieldTypeVisitor
.create(List.of(new WindowConnectionAdapter(scrollCursorStrategy),
new SliceConnectionAdapter(scrollCursorStrategy)));
return (builder) -> builder.typeVisitors(List.of(connectionFieldTypeVisitor));
}
return (builder) -> {
};
}
}
static class GraphQlResourcesRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("graphql/**/*.graphqls").registerPattern("graphql/**/*.gqls");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\GraphQlAutoConfiguration.java | 2 |
请完成以下Java代码 | public String getA_State ()
{
return (String)get_Value(COLUMNNAME_A_State);
}
/** Set Tax Entity.
@param A_Tax_Entity Tax Entity */
public void setA_Tax_Entity (String A_Tax_Entity)
{
set_Value (COLUMNNAME_A_Tax_Entity, A_Tax_Entity);
}
/** Get Tax Entity.
@return Tax Entity */
public String getA_Tax_Entity ()
{
return (String)get_Value(COLUMNNAME_A_Tax_Entity);
}
/** Set Text Message. | @param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Tax.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CounterService {
private ConcurrentMap<String, AtomicLong> namedCounterMap = new ConcurrentHashMap<>();
@Cacheable("Counters")
public long getCachedCount(String counterName) {
return getCount(counterName);
}
@CachePut("Counters")
public long getCount(String counterName) {
AtomicLong counter = this.namedCounterMap.get(counterName);
if (counter == null) { | counter = new AtomicLong(0L);
AtomicLong existingCounter = this.namedCounterMap.putIfAbsent(counterName, counter);
counter = existingCounter != null ? existingCounter : counter;
}
return counter.incrementAndGet();
}
@CacheEvict("Counters")
public void resetCounter(String counterName) {
this.namedCounterMap.remove(counterName);
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\look-aside\src\main\java\example\app\caching\lookaside\service\CounterService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class ArticleRepositoryAdapter implements ArticleRepository {
private final TagJpaRepository tagJpaRepository;
private final ArticleJpaRepository articleJpaRepository;
private final ArticleCommentJpaRepository articleCommentJpaRepository;
private final ArticleFavoriteJpaRepository articleFavoriteJpaRepository;
@Override
public Article save(Article article) {
return articleJpaRepository.save(article);
}
@Override
@Transactional
public Article save(Article article, Collection<Tag> tags) {
var savedArticle = save(article);
for (var tag : tagJpaRepository.saveAll(tags)) {
savedArticle.addTag(new ArticleTag(savedArticle, tag));
}
return savedArticle;
}
@Override
public List<Article> findAll(ArticleFacets facets) {
var pageable = PageRequest.of(facets.page(), facets.size());
var spec = Specification.where(ArticleSpecifications.hasAuthorName(facets.author()))
.or(ArticleSpecifications.hasTagName(facets.tag()))
.or(ArticleSpecifications.hasFavoritedUsername(facets.favorited()));
return articleJpaRepository.findAll(spec, pageable).getContent();
}
@Override
public Optional<Article> findBySlug(String slug) {
return articleJpaRepository.findBySlug(slug);
}
@Override | public List<Article> findByAuthors(Collection<User> authors, ArticleFacets facets) {
return articleJpaRepository
.findByAuthorInOrderByCreatedAtDesc(authors, PageRequest.of(facets.page(), facets.size()))
.getContent();
}
@Override
@Transactional(readOnly = true)
public ArticleDetails findArticleDetails(Article article) {
int totalFavorites = articleFavoriteJpaRepository.countByArticle(article);
return ArticleDetails.unauthenticated(article, totalFavorites);
}
@Override
@Transactional(readOnly = true)
public ArticleDetails findArticleDetails(User requester, Article article) {
int totalFavorites = articleFavoriteJpaRepository.countByArticle(article);
boolean favorited = articleFavoriteJpaRepository.existsByUserAndArticle(requester, article);
return new ArticleDetails(article, totalFavorites, favorited);
}
@Override
@Transactional
public void delete(Article article) {
articleCommentJpaRepository.deleteByArticle(article);
articleJpaRepository.delete(article);
}
@Override
public boolean existsBy(String title) {
return articleJpaRepository.existsByTitle(title);
}
} | repos\realworld-java21-springboot3-main\module\persistence\src\main\java\io\zhc1\realworld\persistence\ArticleRepositoryAdapter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static class Loader {
private final ConfigurableEnvironment environment;
private final ResourceLoader resourceLoader;
private final List<PropertySourceLoader> propertySourceLoaders;
Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
this.environment = environment;
this.resourceLoader = resourceLoader == null ? new DefaultResourceLoader()
: resourceLoader;
this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(
PropertySourceLoader.class, getClass().getClassLoader());
}
void load() {
for (PropertySourceLoader loader : propertySourceLoaders) {
for (String extension : loader.getFileExtensions()) {
String location = "classpath:/" + FlowableDefaultPropertiesEnvironmentPostProcessor.DEFAULT_NAME + "." + extension;
load(location, loader);
}
}
}
void load(String location, PropertySourceLoader loader) {
try { | Resource resource = resourceLoader.getResource(location);
if (!resource.exists()) {
return;
}
String propertyResourceName = "flowableDefaultConfig: [" + location + "]";
List<PropertySource<?>> propertySources = loader.load(propertyResourceName, resource);
if (propertySources == null) {
return;
}
propertySources.forEach(source -> environment.getPropertySources().addLast(source));
} catch (Exception ex) {
throw new IllegalStateException("Failed to load property "
+ "source from location '" + location + "'", ex);
}
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\environment\FlowableDefaultPropertiesEnvironmentPostProcessor.java | 2 |
请完成以下Java代码 | public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage()));
}
/**
* 处理 EntityExist
*/
@ExceptionHandler(value = EntityExistException.class)
public ResponseEntity<ApiError> entityExistException(EntityExistException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getMessage()));
}
/**
* 处理 EntityNotFound
*/
@ExceptionHandler(value = EntityNotFoundException.class)
public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(NOT_FOUND.value(),e.getMessage()));
}
/** | * 处理所有接口数据验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
String message = objectError.getDefaultMessage();
if (objectError instanceof FieldError) {
message = ((FieldError) objectError).getField() + ": " + message;
}
return buildResponseEntity(ApiError.error(message));
}
/**
* 统一返回
*/
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\exception\handler\GlobalExceptionHandler.java | 1 |
请完成以下Java代码 | public Path getPath() {
return this.delegate.getPath();
}
@Override
public boolean isContainedIn(Resource r) {
return this.delegate.isContainedIn(r);
}
@Override
public Iterator<Resource> iterator() {
if (this.delegate instanceof CombinedResource) {
return list().iterator();
}
return List.<Resource>of(this).iterator();
}
@Override
public boolean equals(Object obj) {
return this.delegate.equals(obj);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public boolean exists() {
return this.delegate.exists();
}
@Override
public Spliterator<Resource> spliterator() {
return this.delegate.spliterator();
}
@Override
public boolean isDirectory() {
return this.delegate.isDirectory();
}
@Override
public boolean isReadable() {
return this.delegate.isReadable();
}
@Override
public Instant lastModified() {
return this.delegate.lastModified();
}
@Override
public long length() {
return this.delegate.length();
}
@Override
public URI getURI() {
return this.delegate.getURI();
}
@Override
public String getName() {
return this.delegate.getName();
}
@Override
public String getFileName() {
return this.delegate.getFileName();
}
@Override
public InputStream newInputStream() throws IOException {
return this.delegate.newInputStream();
}
@Override
@SuppressWarnings({ "deprecation", "removal" })
public ReadableByteChannel newReadableByteChannel() throws IOException {
return this.delegate.newReadableByteChannel();
}
@Override
public List<Resource> list() {
return asLoaderHidingResources(this.delegate.list());
}
private boolean nonLoaderResource(Resource resource) {
return !resource.getPath().startsWith(this.loaderBasePath); | }
private List<Resource> asLoaderHidingResources(Collection<Resource> resources) {
return resources.stream().filter(this::nonLoaderResource).map(this::asLoaderHidingResource).toList();
}
private Resource asLoaderHidingResource(Resource resource) {
return (resource instanceof LoaderHidingResource) ? resource : new LoaderHidingResource(this.base, resource);
}
@Override
public @Nullable Resource resolve(String subUriPath) {
if (subUriPath.startsWith(LOADER_RESOURCE_PATH_PREFIX)) {
return null;
}
Resource resolved = this.delegate.resolve(subUriPath);
return (resolved != null) ? new LoaderHidingResource(this.base, resolved) : null;
}
@Override
public boolean isAlias() {
return this.delegate.isAlias();
}
@Override
public URI getRealURI() {
return this.delegate.getRealURI();
}
@Override
public void copyTo(Path destination) throws IOException {
this.delegate.copyTo(destination);
}
@Override
public Collection<Resource> getAllResources() {
return asLoaderHidingResources(this.delegate.getAllResources());
}
@Override
public String toString() {
return this.delegate.toString();
}
} | repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\LoaderHidingResource.java | 1 |
请完成以下Spring Boot application配置 | # Configuration file
# key = value
greeting=Good morning
quarkus.datasource.db-kind = h2
quarkus.datasource.jdbc.url = jdbc:h2:tcp://localhost/mem:test
quarkus.hibernate-orm.database.generation = drop-and-create
| %custom-profile.quarkus.datasource.jdbc.url = jdbc:h2:file:./testdb
quarkus.http.test-port=0 | repos\tutorials-master\quarkus-modules\quarkus\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>(16);
claims.put( CLAIM_KEY_USERNAME, userDetails.getUsername() );
return Jwts.builder()
.setClaims( claims )
.setExpiration( new Date( Instant.now().toEpochMilli() + EXPIRATION_TIME ) )
.signWith( SignatureAlgorithm.HS512, SECRET )
.compact();
}
/**
* 验证JWT
*/
public Boolean validateToken(String token, UserDetails userDetails) {
User user = (User) userDetails;
String username = getUsernameFromToken( token );
return (username.equals( user.getUsername() ) && !isTokenExpired( token ));
}
/**
* 获取token是否过期
*/
public Boolean isTokenExpired(String token) {
Date expiration = getExpirationDateFromToken( token );
return expiration.before( new Date() );
}
/**
* 根据token获取username
*/
public String getUsernameFromToken(String token) {
String username = getClaimsFromToken( token ).getSubject();
return username;
}
/** | * 获取token的过期时间
*/
public Date getExpirationDateFromToken(String token) {
Date expiration = getClaimsFromToken( token ).getExpiration();
return expiration;
}
/**
* 解析JWT
*/
private Claims getClaimsFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey( SECRET )
.parseClaimsJws( token )
.getBody();
return claims;
}
} | repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\utils\JwtTokenUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected BeanDefinition createInterceptorDefinition(Node node) {
Element interceptMethodsElt = (Element) node;
BeanDefinitionBuilder interceptor = BeanDefinitionBuilder
.rootBeanDefinition(MethodSecurityInterceptor.class);
// Default to autowiring to pick up after invocation mgr
interceptor.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
String accessManagerId = interceptMethodsElt.getAttribute(ATT_ACCESS_MGR);
if (!StringUtils.hasText(accessManagerId)) {
accessManagerId = BeanIds.METHOD_ACCESS_MANAGER;
}
interceptor.addPropertyValue("accessDecisionManager", new RuntimeBeanReference(accessManagerId));
interceptor.addPropertyValue("authenticationManager",
new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER));
// Lookup parent bean information
String parentBeanClass = ((Element) interceptMethodsElt.getParentNode()).getAttribute("class");
// Parse the included methods
List<Element> methods = DomUtils.getChildElementsByTagName(interceptMethodsElt, Elements.PROTECT);
Map<String, BeanDefinition> mappings = new ManagedMap<>();
for (Element protectmethodElt : methods) {
BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder.rootBeanDefinition(SecurityConfig.class); | attributeBuilder.setFactoryMethod("createListFromCommaDelimitedString");
attributeBuilder.addConstructorArgValue(protectmethodElt.getAttribute(ATT_ACCESS));
// Support inference of class names
String methodName = protectmethodElt.getAttribute(ATT_METHOD);
if (methodName.lastIndexOf(".") == -1) {
if (parentBeanClass != null && !"".equals(parentBeanClass)) {
methodName = parentBeanClass + "." + methodName;
}
}
mappings.put(methodName, attributeBuilder.getBeanDefinition());
}
BeanDefinition metadataSource = new RootBeanDefinition(MapBasedMethodSecurityMetadataSource.class);
metadataSource.getConstructorArgumentValues().addGenericArgumentValue(mappings);
interceptor.addPropertyValue("securityMetadataSource", metadataSource);
return interceptor.getBeanDefinition();
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\InterceptMethodsBeanDefinitionDecorator.java | 2 |
请完成以下Java代码 | public int getR_RequestProcessorLog_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestProcessorLog_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
public void setSummary (String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Summary.
@return Textual summary of this request
*/
public String getSummary ()
{
return (String)get_Value(COLUMNNAME_Summary);
} | /** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestProcessorLog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PPOrderWeightingRunRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
public PPOrderWeightingRun getById(final PPOrderWeightingRunId id)
{
final PPOrderWeightingRunLoaderAndSaver loader = new PPOrderWeightingRunLoaderAndSaver();
return loader.getById(id);
}
public SeqNo getNextLineNo(final PPOrderWeightingRunId weightingRunId)
{
final int lastLineNo = queryBL.createQueryBuilder(I_PP_Order_Weighting_RunCheck.class)
.addEqualsFilter(I_PP_Order_Weighting_RunCheck.COLUMNNAME_PP_Order_Weighting_Run_ID, weightingRunId)
.create()
.maxInt(I_PP_Order_Weighting_RunCheck.COLUMNNAME_Line);
return SeqNo.ofInt(lastLineNo).next();
}
public void save(@NonNull final PPOrderWeightingRun weightingRun)
{
final PPOrderWeightingRunLoaderAndSaver saver = new PPOrderWeightingRunLoaderAndSaver();
saver.save(weightingRun);
}
public UomId getUomId(final PPOrderWeightingRunId id)
{
final PPOrderWeightingRunLoaderAndSaver loader = new PPOrderWeightingRunLoaderAndSaver();
return loader.getUomId(id);
}
public void updateWhileSaving(
@NonNull final I_PP_Order_Weighting_Run record,
@NonNull final Consumer<PPOrderWeightingRun> consumer)
{
final PPOrderWeightingRunId runId = PPOrderWeightingRunLoaderAndSaver.extractId(record);
final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver();
loaderAndSaver.addToCacheAndAvoidSaving(record);
loaderAndSaver.updateById(runId, consumer);
}
public void updateById(
@NonNull final PPOrderWeightingRunId runId,
@NonNull final Consumer<PPOrderWeightingRun> consumer) | {
final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver();
loaderAndSaver.updateById(runId, consumer);
}
public void deleteChecks(final PPOrderWeightingRunId runId)
{
queryBL.createQueryBuilder(I_PP_Order_Weighting_RunCheck.class)
.addEqualsFilter(I_PP_Order_Weighting_RunCheck.COLUMNNAME_PP_Order_Weighting_Run_ID, runId)
.create()
.delete();
}
public PPOrderWeightingRunCheckId addRunCheck(
@NonNull final PPOrderWeightingRunId weightingRunId,
@NonNull final SeqNo lineNo,
@NonNull final Quantity weight,
@NonNull final OrgId orgId)
{
final I_PP_Order_Weighting_RunCheck record = InterfaceWrapperHelper.newInstance(I_PP_Order_Weighting_RunCheck.class);
record.setAD_Org_ID(orgId.getRepoId());
record.setPP_Order_Weighting_Run_ID(weightingRunId.getRepoId());
record.setLine(lineNo.toInt());
record.setWeight(weight.toBigDecimal());
record.setC_UOM_ID(weight.getUomId().getRepoId());
InterfaceWrapperHelper.save(record);
return PPOrderWeightingRunCheckId.ofRepoId(weightingRunId, record.getPP_Order_Weighting_RunCheck_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunRepository.java | 2 |
请完成以下Java代码 | public boolean isMarkerVisible() {
return isMarkerVisibleAttribute.getValue(this);
}
public void setMarkerVisible(boolean isMarkerVisible) {
isMarkerVisibleAttribute.setValue(this, isMarkerVisible);
}
public boolean isMessageVisible() {
return isMessageVisibleAttribute.getValue(this);
}
public void setMessageVisible(boolean isMessageVisible) {
isMessageVisibleAttribute.setValue(this, isMessageVisible);
}
public ParticipantBandKind getParticipantBandKind() {
return participantBandKindAttribute.getValue(this);
} | public void setParticipantBandKind(ParticipantBandKind participantBandKind) {
participantBandKindAttribute.setValue(this, participantBandKind);
}
public BpmnShape getChoreographyActivityShape() {
return choreographyActivityShapeAttribute.getReferenceTargetElement(this);
}
public void setChoreographyActivityShape(BpmnShape choreographyActivityShape) {
choreographyActivityShapeAttribute.setReferenceTargetElement(this, choreographyActivityShape);
}
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\BpmnShapeImpl.java | 1 |
请完成以下Java代码 | private void checkAuthorizationOfStartSignals(final CommandContext commandContext,
List<EventSubscriptionEntity> startSignalEventSubscriptions, Map<String, ProcessDefinitionEntity> processDefinitions) {
// check authorization for process definition
for (EventSubscriptionEntity signalStartEventSubscription : startSignalEventSubscriptions) {
ProcessDefinitionEntity processDefinition = processDefinitions.get(signalStartEventSubscription.getId());
if (processDefinition != null) {
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkCreateProcessInstance(processDefinition);
}
}
}
}
private void notifyExecutions(List<EventSubscriptionEntity> catchSignalEventSubscription) {
for (EventSubscriptionEntity signalEventSubscriptionEntity : catchSignalEventSubscription) {
if (isActiveEventSubscription(signalEventSubscriptionEntity)) {
signalEventSubscriptionEntity.eventReceived(builder.getVariables(), false);
}
}
}
private boolean isActiveEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) {
ExecutionEntity execution = signalEventSubscriptionEntity.getExecution();
return !execution.isEnded() && !execution.isCanceled();
}
private void startProcessInstances(List<EventSubscriptionEntity> startSignalEventSubscriptions, Map<String, ProcessDefinitionEntity> processDefinitions) {
for (EventSubscriptionEntity signalStartEventSubscription : startSignalEventSubscriptions) {
ProcessDefinitionEntity processDefinition = processDefinitions.get(signalStartEventSubscription.getId());
if (processDefinition != null) {
ActivityImpl signalStartEvent = processDefinition.findActivity(signalStartEventSubscription.getActivityId());
PvmProcessInstance processInstance = processDefinition.createProcessInstanceForInitial(signalStartEvent);
processInstance.start(builder.getVariables());
} | }
}
protected List<EventSubscriptionEntity> filterIntermediateSubscriptions(List<EventSubscriptionEntity> subscriptions) {
List<EventSubscriptionEntity> result = new ArrayList<EventSubscriptionEntity>();
for (EventSubscriptionEntity subscription : subscriptions) {
if (subscription.getExecutionId() != null) {
result.add(subscription);
}
}
return result;
}
protected List<EventSubscriptionEntity> filterStartSubscriptions(List<EventSubscriptionEntity> subscriptions) {
List<EventSubscriptionEntity> result = new ArrayList<EventSubscriptionEntity>();
for (EventSubscriptionEntity subscription : subscriptions) {
if (subscription.getExecutionId() == null) {
result.add(subscription);
}
}
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SignalEventReceivedCmd.java | 1 |
请完成以下Java代码 | protected DbOperation performTaskMetricsCleanup() {
return Context
.getCommandContext()
.getMeterLogManager()
.deleteTaskMetricsByRemovalTime(ClockUtil.getCurrentTime(), getTaskMetricsTimeToLive(),
configuration.getMinuteFrom(), configuration.getMinuteTo(), getBatchSize());
}
protected Map<String, Long> reportMetrics() {
Map<String, Long> reports = new HashMap<>();
DbOperation deleteOperationProcessInstance = deleteOperations.get(HistoricProcessInstanceEntity.class);
if (deleteOperationProcessInstance != null) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_PROCESS_INSTANCES, (long) deleteOperationProcessInstance.getRowsAffected());
}
DbOperation deleteOperationDecisionInstance = deleteOperations.get(HistoricDecisionInstanceEntity.class);
if (deleteOperationDecisionInstance != null) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_DECISION_INSTANCES, (long) deleteOperationDecisionInstance.getRowsAffected());
}
DbOperation deleteOperationBatch = deleteOperations.get(HistoricBatchEntity.class);
if (deleteOperationBatch != null) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_BATCH_OPERATIONS, (long) deleteOperationBatch.getRowsAffected());
}
DbOperation deleteOperationTaskMetric = deleteOperations.get(TaskMeterLogEntity.class);
if (deleteOperationTaskMetric != null) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_TASK_METRICS, (long) deleteOperationTaskMetric.getRowsAffected());
}
return reports;
}
protected boolean isDmnEnabled() {
return Context
.getProcessEngineConfiguration()
.isDmnEnabled();
}
protected Integer getTaskMetricsTimeToLive() {
return Context
.getProcessEngineConfiguration()
.getParsedTaskMetricsTimeToLive();
} | protected boolean shouldRescheduleNow() {
int batchSize = getBatchSize();
for (DbOperation deleteOperation : deleteOperations.values()) {
if (deleteOperation.getRowsAffected() == batchSize) {
return true;
}
}
return false;
}
public int getBatchSize() {
return Context
.getProcessEngineConfiguration()
.getHistoryCleanupBatchSize();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupRemovalTime.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LettuceConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration();
redisConf.setHostName(env.getProperty("spring.redis.host"));
redisConf.setPort(Integer.parseInt(env.getProperty("spring.redis.port")));
redisConf.setPassword(RedisPassword.of(env.getProperty("spring.redis.password")));
return new LettuceConnectionFactory(redisConf);
}
@Bean
public RedisCacheConfiguration cacheConfiguration() {
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.disableCachingNullValues();
return cacheConfig;
}
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager rcm = RedisCacheManager.builder(redisConnectionFactory())
.cacheDefaults(cacheConfiguration())
.transactionAware()
.build();
return rcm;
} | /**
* 自定义缓存key的生成类实现
*/
@Bean(name = "myKeyGenerator")
public KeyGenerator myKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... params) {
logger.info("自定义缓存,使用第一参数作为缓存key,params = " + Arrays.toString(params));
// 仅仅用于测试,实际不可能这么写
return params[0];
}
};
}
} | repos\SpringBootBucket-master\springboot-cache\src\main\java\com\xncoding\trans\config\RedisCacheConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Job getJobById(@PathVariable UUID id) throws ThingsboardException {
JobId jobId = new JobId(id);
return checkJobId(jobId, Operation.READ);
}
@GetMapping("/jobs")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
public PageData<Job> getJobs(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true)
@RequestParam int pageSize,
@Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true)
@RequestParam int page,
@Parameter(description = "Case-insensitive 'substring' filter based on job's description")
@RequestParam(required = false) String textSearch,
@Parameter(description = SORT_PROPERTY_DESCRIPTION)
@RequestParam(required = false) String sortProperty,
@Parameter(description = SORT_ORDER_DESCRIPTION)
@RequestParam(required = false) String sortOrder,
@RequestParam(required = false) List<JobType> types,
@RequestParam(required = false) List<JobStatus> statuses,
@RequestParam(required = false) List<UUID> entities,
@RequestParam(required = false) Long startTime,
@RequestParam(required = false) Long endTime) throws ThingsboardException {
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
JobFilter filter = JobFilter.builder()
.types(types)
.statuses(statuses)
.entities(entities)
.startTime(startTime)
.endTime(endTime) | .build();
return jobService.findJobsByFilter(getTenantId(), filter, pageLink);
}
@PostMapping("/job/{id}/cancel")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
public void cancelJob(@PathVariable UUID id) throws ThingsboardException {
JobId jobId = new JobId(id);
checkJobId(jobId, Operation.WRITE);
jobManager.cancelJob(getTenantId(), jobId);
}
@PostMapping("/job/{id}/reprocess")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
public void reprocessJob(@PathVariable UUID id) throws ThingsboardException {
JobId jobId = new JobId(id);
checkJobId(jobId, Operation.WRITE);
jobManager.reprocessJob(getTenantId(), jobId);
}
@DeleteMapping("/job/{id}")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
public void deleteJob(@PathVariable UUID id) throws ThingsboardException {
JobId jobId = new JobId(id);
checkJobId(jobId, Operation.DELETE);
jobService.deleteJob(getTenantId(), jobId);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\JobController.java | 2 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionService.class, DMN_ELEMENT_DECISION_SERVICE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(NamedElement.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionService>() {
public DecisionService newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionServiceImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
outputDecisionRefCollection = sequenceBuilder.elementCollection(OutputDecisionReference.class)
.required()
.uriElementReferenceCollection(Decision.class)
.build();
encapsulatedDecisionRefCollection = sequenceBuilder.elementCollection(EncapsulatedDecisionReference.class) | .uriElementReferenceCollection(Decision.class)
.build();
inputDecisionRefCollection = sequenceBuilder.elementCollection(InputDecisionReference.class)
.uriElementReferenceCollection(Decision.class)
.build();
inputDataRefCollection = sequenceBuilder.elementCollection(InputDataReference.class)
.uriElementReferenceCollection(InputData.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionServiceImpl.java | 1 |
请完成以下Java代码 | public @NonNull ShipperTransportationId getOrCreate(@NonNull final CreateShipperTransportationRequest request)
{
return getSingleByQuery(ShipperTransportationQuery.builder()
.shipperId(request.getShipperId())
.shipperBPartnerAndLocationId(request.getShipperBPartnerAndLocationId())
.shipDate(request.getShipDate())
.orgId(request.getOrgId())
.build())
.orElseGet(() -> create(request));
}
@Override
public ImmutableList<OrderId> retrieveOrderIds(@NonNull final ShipperTransportationId shipperTransportationId)
{
return queryBL
.createQueryBuilder(I_M_ShippingPackage.class)
.addEqualsFilter(I_M_ShippingPackage.COLUMNNAME_M_ShipperTransportation_ID, shipperTransportationId)
.addOnlyActiveRecordsFilter()
.create() | .listDistinct(I_M_ShippingPackage.COLUMNNAME_C_Order_ID, OrderId.class);
}
@Override
public Collection<I_M_ShipperTransportation> getByQuery(@NonNull final ShipperTransportationQuery query)
{
return toSqlQuery(query)
.list();
}
@Override
public boolean anyMatch(@NonNull final ShipperTransportationQuery query)
{
return toSqlQuery(query)
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\api\impl\ShipperTransportationDAO.java | 1 |
请完成以下Java代码 | public void setDefaultFailureUrl(String defaultFailureUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl),
() -> "'" + defaultFailureUrl + "' is not a valid redirect URL");
this.defaultFailureUrl = defaultFailureUrl;
}
protected boolean isUseForward() {
return this.forwardToDestination;
}
/**
* If set to <tt>true</tt>, performs a forward to the failure destination URL instead
* of a redirect. Defaults to <tt>false</tt>.
*/
public void setUseForward(boolean forwardToDestination) {
this.forwardToDestination = forwardToDestination;
}
/**
* Allows overriding of the behaviour when redirecting to a target URL.
*/
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy; | }
protected RedirectStrategy getRedirectStrategy() {
return this.redirectStrategy;
}
protected boolean isAllowSessionCreation() {
return this.allowSessionCreation;
}
public void setAllowSessionCreation(boolean allowSessionCreation) {
this.allowSessionCreation = allowSessionCreation;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\SimpleUrlAuthenticationFailureHandler.java | 1 |
请完成以下Java代码 | public I_M_HU_Attribute getM_HU_Attribute()
{
return huAttribute;
}
@Override
protected void setInternalValueString(final String value)
{
huAttribute.setValue(value);
valueString = value;
}
@Override
protected void setInternalValueNumber(final BigDecimal value)
{
huAttribute.setValueNumber(value);
valueNumber = value;
}
@Override
protected String getInternalValueString()
{
return valueString;
}
@Override
protected BigDecimal getInternalValueNumber()
{
return valueNumber;
}
@Override
protected String getInternalValueStringInitial()
{
return huAttribute.getValueInitial();
}
@Override
protected BigDecimal getInternalValueNumberInitial()
{
return huAttribute.getValueNumberInitial();
}
@Override
protected void setInternalValueStringInitial(final String value)
{
huAttribute.setValueInitial(value);
}
@Override
protected void setInternalValueNumberInitial(final BigDecimal value)
{
huAttribute.setValueNumberInitial(value);
}
@Override
protected final void onValueChanged(final Object valueOld, final Object valueNew)
{
saveIfNeeded();
}
/**
* Save to database if {@link #isSaveOnChange()}.
*/ | private final void saveIfNeeded()
{
if (!saveOnChange)
{
return;
}
save();
}
/**
* Save to database. This method is saving no matter what {@link #isSaveOnChange()} says.
*/
final void save()
{
// Make sure the storage was not disposed
assertNotDisposed();
// Make sure HU Attribute contains the right/fresh data
huAttribute.setValue(valueString);
huAttribute.setValueNumber(valueNumber);
huAttribute.setValueDate(TimeUtil.asTimestamp(valueDate));
getHUAttributesDAO().save(huAttribute);
}
@Override
public boolean isNew()
{
return huAttribute.getM_HU_Attribute_ID() <= 0;
}
@Override
protected void setInternalValueDate(Date value)
{
huAttribute.setValueDate(TimeUtil.asTimestamp(value));
this.valueDate = value;
}
@Override
protected Date getInternalValueDate()
{
return valueDate;
}
@Override
protected void setInternalValueDateInitial(Date value)
{
huAttribute.setValueDateInitial(TimeUtil.asTimestamp(value));
}
@Override
protected Date getInternalValueDateInitial()
{
return huAttribute.getValueDateInitial();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\HUAttributeValue.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyReserved ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReserved);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Quantity to Order.
@param QtyToOrder Quantity to Order */
public void setQtyToOrder (BigDecimal QtyToOrder)
{
set_Value (COLUMNNAME_QtyToOrder, QtyToOrder);
}
/** Get Quantity to Order.
@return Quantity to Order */
public BigDecimal getQtyToOrder ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder);
if (bd == null)
return Env.ZERO;
return bd;
}
/** ReplenishmentCreate AD_Reference_ID=329 */
public static final int REPLENISHMENTCREATE_AD_Reference_ID=329;
/** Purchase Order = POO */
public static final String REPLENISHMENTCREATE_PurchaseOrder = "POO";
/** Requisition = POR */
public static final String REPLENISHMENTCREATE_Requisition = "POR";
/** Inventory Move = MMM */
public static final String REPLENISHMENTCREATE_InventoryMove = "MMM";
/** Distribution Order = DOO */
public static final String REPLENISHMENTCREATE_DistributionOrder = "DOO";
/** Set Create.
@param ReplenishmentCreate
Create from Replenishment
*/
public void setReplenishmentCreate (String ReplenishmentCreate)
{
set_Value (COLUMNNAME_ReplenishmentCreate, ReplenishmentCreate);
}
/** Get Create.
@return Create from Replenishment
*/ | public String getReplenishmentCreate ()
{
return (String)get_Value(COLUMNNAME_ReplenishmentCreate);
}
/** ReplenishType AD_Reference_ID=164 */
public static final int REPLENISHTYPE_AD_Reference_ID=164;
/** Maintain Maximum Level = 2 */
public static final String REPLENISHTYPE_MaintainMaximumLevel = "2";
/** Manual = 0 */
public static final String REPLENISHTYPE_Manual = "0";
/** Reorder below Minimum Level = 1 */
public static final String REPLENISHTYPE_ReorderBelowMinimumLevel = "1";
/** Custom = 9 */
public static final String REPLENISHTYPE_Custom = "9";
/** Set Replenish Type.
@param ReplenishType
Method for re-ordering a product
*/
public void setReplenishType (String ReplenishType)
{
set_Value (COLUMNNAME_ReplenishType, ReplenishType);
}
/** Get Replenish Type.
@return Method for re-ordering a product
*/
public String getReplenishType ()
{
return (String)get_Value(COLUMNNAME_ReplenishType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_Replenish.java | 1 |
请完成以下Java代码 | public int getDefaultFailedJobWaitTime() {
return defaultFailedJobWaitTime;
}
public ProcessEngineConfiguration setDefaultFailedJobWaitTime(int defaultFailedJobWaitTime) {
this.defaultFailedJobWaitTime = defaultFailedJobWaitTime;
return this;
}
public int getAsyncFailedJobWaitTime() {
return asyncFailedJobWaitTime;
}
public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) {
this.asyncFailedJobWaitTime = asyncFailedJobWaitTime;
return this;
}
public boolean isEnableProcessDefinitionInfoCache() {
return enableProcessDefinitionInfoCache;
}
public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) {
this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache; | return this;
}
public ProcessEngineConfiguration setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) {
this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks;
return this;
}
public boolean isCopyVariablesToLocalForTasks() {
return copyVariablesToLocalForTasks;
}
public void setEngineAgendaFactory(ActivitiEngineAgendaFactory engineAgendaFactory) {
this.engineAgendaFactory = engineAgendaFactory;
}
public ActivitiEngineAgendaFactory getEngineAgendaFactory() {
return engineAgendaFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet) {
return new DispatcherServletRegistrationBean(dispatcherServlet, "/");
}
@Bean(name = DispatcherServlet.HANDLER_MAPPING_BEAN_NAME)
CompositeHandlerMapping compositeHandlerMapping() {
return new CompositeHandlerMapping();
}
@Bean(name = DispatcherServlet.HANDLER_ADAPTER_BEAN_NAME)
CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) {
return new CompositeHandlerAdapter(beanFactory);
}
@Bean(name = DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME)
CompositeHandlerExceptionResolver compositeHandlerExceptionResolver() {
return new CompositeHandlerExceptionResolver();
}
@Bean
@ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class })
RequestContextFilter requestContextFilter() {
return new OrderedRequestContextFilter();
}
/** | * {@link WebServerFactoryCustomizer} to add an {@link ErrorPage} so that the
* {@link ManagementErrorEndpoint} can be used.
*/
static class ManagementErrorPageCustomizer
implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {
private final WebProperties properties;
ManagementErrorPageCustomizer(WebProperties properties) {
this.properties = properties;
}
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
factory.addErrorPages(new ErrorPage(this.properties.getError().getPath()));
}
@Override
public int getOrder() {
return 10; // Run after ManagementWebServerFactoryCustomizer
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\actuate\web\WebMvcEndpointChildContextConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getREFERENCEQUAL() {
return referencequal;
}
/**
* Sets the value of the referencequal property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEQUAL(String value) {
this.referencequal = value;
}
/**
* Gets the value of the reference property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCE() {
return reference;
}
/**
* Sets the value of the reference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCE(String value) {
this.reference = value;
}
/**
* Gets the value of the referencedate1 property.
*
* @return | * possible object is
* {@link String }
*
*/
public String getREFERENCEDATE1() {
return referencedate1;
}
/**
* Sets the value of the referencedate1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE1(String value) {
this.referencedate1 = value;
}
/**
* Gets the value of the referencedate2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEDATE2() {
return referencedate2;
}
/**
* Sets the value of the referencedate2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE2(String value) {
this.referencedate2 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DRFAD1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Wizard {
@Id
private UUID id;
private String name;
@SortHouse
private String house;
@GenerateSpellPower
private Integer spellPower;
@GenerateUpdatedAtTimestamp
private LocalDateTime updatedAt;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHouse() {
return house;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public Integer getSpellPower() {
return spellPower;
}
} | repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\attributevaluegenerator\Wizard.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonPurchaseOrder
{
@JsonProperty("dateOrdered")
@JsonFormat(shape = JsonFormat.Shape.STRING)
ZonedDateTime dateOrdered;
@JsonProperty("datePromised")
@JsonFormat(shape = JsonFormat.Shape.STRING)
ZonedDateTime datePromised;
@JsonProperty("docStatus")
String docStatus;
@JsonProperty("documentNo")
String documentNo;
@JsonProperty("metasfreshId")
JsonMetasfreshId metasfreshId; | @JsonProperty("pdfAvailable")
boolean pdfAvailable;
@Builder
@JsonCreator
public JsonPurchaseOrder(@JsonProperty("dateOrdered") @NonNull final ZonedDateTime dateOrdered,
@JsonProperty("datePromised") @NonNull final ZonedDateTime datePromised,
@JsonProperty("docStatus") @NonNull final String docStatus,
@JsonProperty("documentNo") @NonNull final String documentNo,
@JsonProperty("metasfreshId") @NonNull final JsonMetasfreshId metasfreshId,
@JsonProperty("pdfAvailable") final boolean pdfAvailable)
{
this.dateOrdered = dateOrdered;
this.datePromised = datePromised;
this.docStatus = docStatus;
this.documentNo = documentNo;
this.metasfreshId = metasfreshId;
this.pdfAvailable = pdfAvailable;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v2\JsonPurchaseOrder.java | 2 |
请完成以下Java代码 | public void validate(MigratingTransitionInstance migratingInstance, MigratingProcessInstance migratingProcessInstance,
MigratingTransitionInstanceValidationReportImpl instanceReport) {
if (isInvalid(migratingInstance)) {
instanceReport.addFailure("There is no migration instruction for this instance's activity");
}
}
@Override
public void validate(MigratingCompensationEventSubscriptionInstance migratingInstance, MigratingProcessInstance migratingProcessInstance,
MigratingActivityInstanceValidationReportImpl ancestorInstanceReport) {
if (isInvalid(migratingInstance)) {
ancestorInstanceReport.addFailure(
"Cannot migrate subscription for compensation handler '" + migratingInstance.getSourceScope().getId() + "'. "
+ "There is no migration instruction for the compensation boundary event");
}
}
@Override
public void validate(MigratingEventScopeInstance migratingInstance, MigratingProcessInstance migratingProcessInstance,
MigratingActivityInstanceValidationReportImpl ancestorInstanceReport) {
if (isInvalid(migratingInstance)) {
ancestorInstanceReport.addFailure(
"Cannot migrate subscription for compensation handler '" + migratingInstance.getEventSubscription().getSourceScope().getId() + "'. "
+ "There is no migration instruction for the compensation start event");
}
} | protected boolean isInvalid(MigratingActivityInstance migratingInstance) {
return hasNoInstruction(migratingInstance) && migratingInstance.getChildren().isEmpty();
}
protected boolean isInvalid(MigratingEventScopeInstance migratingInstance) {
return hasNoInstruction(migratingInstance.getEventSubscription()) && migratingInstance.getChildren().isEmpty();
}
protected boolean isInvalid(MigratingTransitionInstance migratingInstance) {
return hasNoInstruction(migratingInstance);
}
protected boolean isInvalid(MigratingCompensationEventSubscriptionInstance migratingInstance) {
return hasNoInstruction(migratingInstance);
}
protected boolean hasNoInstruction(MigratingProcessElementInstance migratingInstance) {
return migratingInstance.getMigrationInstruction() == null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\NoUnmappedLeafInstanceValidator.java | 1 |
请完成以下Java代码 | protected List<String> getTenantsOfUser(ProcessEngine engine, String userId) {
List<Tenant> tenants = engine.getIdentityService().createTenantQuery()
.userMember(userId)
.includingGroupsOfUser(true)
.list();
List<String> tenantIds = new ArrayList<>();
for(Tenant tenant : tenants) {
tenantIds.add(tenant.getId());
}
return tenantIds;
}
@POST
@Path("/{processEngineName}/logout")
public Response doLogout(@PathParam("processEngineName") String engineName) {
final Authentications authentications = Authentications.getCurrent();
ProcessEngine processEngine = ProcessEngineUtil.lookupProcessEngine(engineName);
if(processEngine == null) {
throw LOGGER.invalidRequestEngineNotFoundForName(engineName);
}
// remove authentication for process engine
if(authentications != null) {
UserAuthentication removedAuthentication = authentications.removeByEngineName(engineName);
if(isWebappsAuthenticationLoggingEnabled(processEngine) && removedAuthentication != null) {
LOGGER.infoWebappLogout(removedAuthentication.getName());
}
}
return Response.ok().build();
} | protected Response unauthorized() {
return Response.status(Status.UNAUTHORIZED).build();
}
protected Response forbidden() {
return Response.status(Status.FORBIDDEN).build();
}
protected Response notFound() {
return Response.status(Status.NOT_FOUND).build();
}
private boolean isWebappsAuthenticationLoggingEnabled(ProcessEngine processEngine) {
return ((ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration()).isWebappsAuthenticationLoggingEnabled();
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\UserAuthenticationResource.java | 1 |
请完成以下Java代码 | public void saveOrUpdate(final @NonNull OrgId orgId, final BPRelation rel)
{
final I_C_BP_Relation relation;
if (rel.getBpRelationId() != null)
{
relation = InterfaceWrapperHelper.load(rel.getBpRelationId(), I_C_BP_Relation.class);
}
else
{
final Optional<I_C_BP_Relation> bpartnerRelation = getRelationsForSourceBpartner(rel.getBpartnerId())
.filter(r -> r.getC_BPartnerRelation_ID() == rel.getTargetBPartnerId().getRepoId())
.findFirst();
relation = bpartnerRelation.orElseGet(() -> InterfaceWrapperHelper.newInstance(I_C_BP_Relation.class));
}
relation.setAD_Org_ID(orgId.getRepoId());
relation.setC_BPartner_ID(rel.getBpartnerId().getRepoId());
if (rel.getBpRelationId() != null)
{
relation.setC_BPartner_Location_ID(rel.getBpRelationId().getRepoId()); | }
relation.setC_BPartnerRelation_ID(rel.getTargetBPartnerId().getRepoId());
relation.setC_BPartnerRelation_Location_ID(rel.getTargetBPLocationId().getRepoId());
relation.setName(coalesceNotNull(rel.getName(), relation.getName()));
relation.setDescription(coalesce(rel.getDescription(), relation.getDescription()));
relation.setRole(rel.getRole() != null ? rel.getRole().getCode() : relation.getRole());
if (rel.getExternalId() != null)
{
relation.setExternalId(rel.getExternalId().getValue());
}
relation.setIsActive(coalesceNotNull(rel.getActive(), relation.isActive(), true));
relation.setIsBillTo(coalesceNotNull(rel.getBillTo(), relation.isBillTo()));
relation.setIsFetchedFrom(coalesceNotNull(rel.getFetchedFrom(), relation.isFetchedFrom()));
relation.setIsHandOverLocation(coalesceNotNull(rel.getHandoverLocation(), relation.isHandOverLocation()));
relation.setIsPayFrom(coalesceNotNull(rel.getPayFrom(), relation.isPayFrom()));
relation.setIsRemitTo(coalesceNotNull(rel.getRemitTo(), relation.isRemitTo()));
relation.setIsShipTo(coalesceNotNull(rel.getShipTo(), relation.isShipTo()));
InterfaceWrapperHelper.save(relation);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\api\impl\BPRelationDAO.java | 1 |
请完成以下Java代码 | public Object getCredentials() {
return "";
}
/**
* Returns the authorization URI.
* @return the authorization URI
*/
public String getAuthorizationUri() {
return this.authorizationUri;
}
/**
* Returns the client identifier.
* @return the client identifier
*/
public String getClientId() {
return this.clientId;
}
/**
* Returns the redirect uri.
* @return the redirect uri
*/
@Nullable
public String getRedirectUri() {
return this.redirectUri;
}
/** | * Returns the state.
* @return the state
*/
@Nullable
public String getState() {
return this.state;
}
/**
* Returns the requested (or authorized) scope(s).
* @return the requested (or authorized) scope(s), or an empty {@code Set} if not
* available
*/
public Set<String> getScopes() {
return this.scopes;
}
/**
* Returns the additional parameters.
* @return the additional parameters, or an empty {@code Map} if not available
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\AbstractOAuth2AuthorizationCodeRequestAuthenticationToken.java | 1 |
请完成以下Java代码 | public BigDecimal getRoyaltyAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoyaltyAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
/** Set Partner Category.
@param VendorCategory
Product Category of the Business Partner
*/
public void setVendorCategory (String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
/** Get Partner Category.
@return Product Category of the Business Partner
*/
public String getVendorCategory ()
{ | return (String)get_Value(COLUMNNAME_VendorCategory);
}
/** Set Partner Product Key.
@param VendorProductNo
Product Key of the Business Partner
*/
public void setVendorProductNo (String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
/** Get Partner Product Key.
@return Product Key of the Business Partner
*/
public String getVendorProductNo ()
{
return (String)get_Value(COLUMNNAME_VendorProductNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_PO.java | 1 |
请完成以下Java代码 | public void ignoredSentryWithMissingCondition(String id) {
logInfo(
"003",
"Sentry with id '{}' will be ignored. Reason: Neither ifPart nor onParts are defined with a condition.",
id
);
}
public void ignoredSentryWithInvalidParts(String id) {
logInfo("004", "Sentry with id '{}' will be ignored. Reason: ifPart and all onParts are not valid.", id);
}
public void ignoredUnsupportedAttribute(String attribute, String element, String id) {
logInfo(
"005",
"The attribute '{}' based on the element '{}' of the sentry with id '{}' is not supported and will be ignored.",
attribute,
element,
id
);
}
public void multipleIgnoredConditions(String id) {
logInfo(
"006",
"The ifPart of the sentry with id '{}' has more than one condition. " +
"Only the first one will be used and the other conditions will be ignored.",
id
);
} | public CmmnTransformException nonMatchingVariableEvents(String id) {
return new CmmnTransformException(exceptionMessage(
"007",
"The variableOnPart of the sentry with id '{}' must have one valid variable event. ",
id
));
}
public CmmnTransformException emptyVariableName(String id) {
return new CmmnTransformException(exceptionMessage(
"008",
"The variableOnPart of the sentry with id '{}' must have variable name. ",
id
));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\CmmnTransformerLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean deleteAiModelById(
@Parameter(
description = "ID of the AI model record",
required = true,
example = "de7900d4-30e2-11f0-9cd2-0242ac120002"
)
@PathVariable UUID modelUuid
) throws ThingsboardException {
var user = getCurrentUser();
var modelId = new AiModelId(modelUuid);
accessControlService.checkPermission(user, Resource.AI_MODEL, Operation.DELETE);
Optional<AiModel> toDelete = aiModelService.findAiModelByTenantIdAndId(user.getTenantId(), modelId);
if (toDelete.isEmpty()) {
return false;
}
accessControlService.checkPermission(user, Resource.AI_MODEL, Operation.DELETE, modelId, toDelete.get());
return tbAiModelService.delete(toDelete.get(), user);
}
@ApiOperation(
value = "Send request to AI chat model (sendChatRequest)", | notes = "Submits a single prompt - made up of an optional system message and a required user message - to the specified AI chat model " +
"and returns either the generated answer or an error envelope." +
TENANT_AUTHORITY_PARAGRAPH
)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/chat")
public DeferredResult<TbChatResponse> sendChatRequest(@Valid @RequestBody TbChatRequest tbChatRequest) {
ChatRequest langChainChatRequest = tbChatRequest.toLangChainChatRequest();
AiChatModelConfig<?> chatModelConfig = tbChatRequest.chatModelConfig();
ListenableFuture<TbChatResponse> future = aiChatModelService.sendChatRequestAsync(chatModelConfig, langChainChatRequest)
.transform(chatResponse -> (TbChatResponse) new TbChatResponse.Success(chatResponse.aiMessage().text()), directExecutor())
.catching(Throwable.class, ex -> new TbChatResponse.Failure(ex.getMessage()), directExecutor());
Integer requestTimeoutSeconds = chatModelConfig.timeoutSeconds();
return requestTimeoutSeconds != null ? wrapFuture(future, Duration.ofSeconds(requestTimeoutSeconds).toMillis()) : wrapFuture(future);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\AiModelController.java | 2 |
请完成以下Java代码 | public class WebAuthnAuthentication extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = -4879907158750659197L;
private final PublicKeyCredentialUserEntity principal;
public WebAuthnAuthentication(PublicKeyCredentialUserEntity principal,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
private WebAuthnAuthentication(Builder<?> builder) {
super(builder);
this.principal = builder.principal;
}
@Override
public void setAuthenticated(boolean authenticated) {
Assert.isTrue(!authenticated, "Cannot set this token to trusted");
super.setAuthenticated(authenticated);
}
@Override
public @Nullable Object getCredentials() {
return null;
}
@Override
public PublicKeyCredentialUserEntity getPrincipal() {
return this.principal;
}
@Override
public String getName() {
return this.principal.getName();
}
@Override
public Builder<?> toBuilder() {
return new Builder<>(this);
}
/**
* A builder of {@link WebAuthnAuthentication} instances
*
* @since 7.0
*/
public static final class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { | private PublicKeyCredentialUserEntity principal;
private Builder(WebAuthnAuthentication token) {
super(token);
this.principal = token.principal;
}
/**
* Use this principal. It must be of type {@link PublicKeyCredentialUserEntity}
* @param principal the principal to use
* @return the {@link Builder} for further configurations
*/
@Override
public B principal(@Nullable Object principal) {
Assert.isInstanceOf(PublicKeyCredentialUserEntity.class, principal,
"principal must be of type PublicKeyCredentialUserEntity");
this.principal = (PublicKeyCredentialUserEntity) principal;
return (B) this;
}
@Override
public WebAuthnAuthentication build() {
return new WebAuthnAuthentication(this);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\WebAuthnAuthentication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class RedisCacheConfiguration {
@Bean
RedisCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers cacheManagerCustomizers,
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
ObjectProvider<RedisCacheManagerBuilderCustomizer> redisCacheManagerBuilderCustomizers,
RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) {
RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(
determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader()));
List<String> cacheNames = cacheProperties.getCacheNames();
if (!cacheNames.isEmpty()) {
builder.initialCacheNames(new LinkedHashSet<>(cacheNames));
}
if (cacheProperties.getRedis().isEnableStatistics()) {
builder.enableStatistics();
}
redisCacheManagerBuilderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return cacheManagerCustomizers.customize(builder.build());
}
private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(
CacheProperties cacheProperties,
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
@Nullable ClassLoader classLoader) {
return redisCacheConfiguration.getIfAvailable(() -> createConfiguration(cacheProperties, classLoader));
}
private org.springframework.data.redis.cache.RedisCacheConfiguration createConfiguration(
CacheProperties cacheProperties, @Nullable ClassLoader classLoader) {
Redis redisProperties = cacheProperties.getRedis();
org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration | .defaultCacheConfig();
config = config
.serializeValuesWith(SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
} | repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\RedisCacheConfiguration.java | 2 |
请完成以下Java代码 | protected BigDecimal getBalance() {return BigDecimal.ZERO;}
@Override
protected List<Fact> createFacts(final AcctSchema as)
{
if (!AcctSchemaId.equals(as.getId(), costRevaluation.getAcctSchemaId()))
{
return ImmutableList.of();
}
setC_Currency_ID(as.getCurrencyId());
final Fact fact = new Fact(this, as, PostingType.Actual);
getDocLines().forEach(line -> createFactsForLine(fact, line));
return ImmutableList.of(fact);
}
private void createFactsForLine(@NonNull final Fact fact, @NonNull final DocLine_CostRevaluation docLine)
{
final AcctSchema acctSchema = fact.getAcctSchema();
final CostAmount costs = docLine.getCreateCosts(acctSchema);
//
// Revenue
// -------------------
// Product Asset DR
// Revenue CR
if (costs.signum() >= 0)
{
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(costs, null)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd(); | fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Revenue_Acct, acctSchema))
.setAmtSource(null, costs)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
}
//
// Expense
// ------------------------------------
// Product Asset CR
// Expense DR
else // deltaAmountToBook.signum() < 0
{
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(null, costs.negate())
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(costs.negate(), null)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_CostRevaluation.java | 1 |
请完成以下Java代码 | public class CompensateEventDefinition extends EventDefinition {
protected String activityRef;
protected boolean waitForCompletion = true;
public String getActivityRef() {
return activityRef;
}
public void setActivityRef(String activityRef) {
this.activityRef = activityRef;
}
public boolean isWaitForCompletion() {
return waitForCompletion;
} | public void setWaitForCompletion(boolean waitForCompletion) {
this.waitForCompletion = waitForCompletion;
}
public CompensateEventDefinition clone() {
CompensateEventDefinition clone = new CompensateEventDefinition();
clone.setValues(this);
return clone;
}
public void setValues(CompensateEventDefinition otherDefinition) {
super.setValues(otherDefinition);
setActivityRef(otherDefinition.getActivityRef());
setWaitForCompletion(otherDefinition.isWaitForCompletion());
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\CompensateEventDefinition.java | 1 |
请完成以下Java代码 | public class SequenceFlowImpl extends FlowElementImpl implements SequenceFlow {
protected static AttributeReference<FlowNode> sourceRefAttribute;
protected static AttributeReference<FlowNode> targetRefAttribute;
protected static Attribute<Boolean> isImmediateAttribute;
protected static ChildElement<ConditionExpression> conditionExpressionCollection;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(SequenceFlow.class, BPMN_ELEMENT_SEQUENCE_FLOW)
.namespaceUri(BPMN20_NS)
.extendsType(FlowElement.class)
.instanceProvider(new ModelTypeInstanceProvider<SequenceFlow>() {
public SequenceFlow newInstance(ModelTypeInstanceContext instanceContext) {
return new SequenceFlowImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SOURCE_REF)
.required()
.idAttributeReference(FlowNode.class)
.build();
targetRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TARGET_REF)
.required()
.idAttributeReference(FlowNode.class)
.build();
isImmediateAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_IMMEDIATE)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
conditionExpressionCollection = sequenceBuilder.element(ConditionExpression.class)
.build();
typeBuilder.build();
}
public SequenceFlowImpl(ModelTypeInstanceContext context) {
super(context);
}
@Override
public SequenceFlowBuilder builder() {
return new SequenceFlowBuilder((BpmnModelInstance) modelInstance, this);
}
public FlowNode getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(FlowNode source) {
sourceRefAttribute.setReferenceTargetElement(this, source);
}
public FlowNode getTarget() {
return targetRefAttribute.getReferenceTargetElement(this);
}
public void setTarget(FlowNode target) {
targetRefAttribute.setReferenceTargetElement(this, target); | }
public boolean isImmediate() {
return isImmediateAttribute.getValue(this);
}
public void setImmediate(boolean isImmediate) {
isImmediateAttribute.setValue(this, isImmediate);
}
public ConditionExpression getConditionExpression() {
return conditionExpressionCollection.getChild(this);
}
public void setConditionExpression(ConditionExpression conditionExpression) {
conditionExpressionCollection.setChild(this, conditionExpression);
}
public void removeConditionExpression() {
conditionExpressionCollection.removeChild(this);
}
public BpmnEdge getDiagramElement() {
return (BpmnEdge) super.getDiagramElement();
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SequenceFlowImpl.java | 1 |
请完成以下Java代码 | public DocumentId getId()
{
return id;
}
@Override
public boolean isProcessed()
{
return false;
}
@Nullable
@Override
public DocumentPath getDocumentPath()
{
return null;
}
public ProductId getProductId()
{
return getProduct().getIdAs(ProductId::ofRepoId);
}
public String getProductName()
{
return getProduct().getDisplayName();
}
public boolean isQtySet()
{
final BigDecimal qty = getQty();
return qty != null && qty.signum() != 0;
}
public ProductsProposalRow withLastShipmentDays(final Integer lastShipmentDays)
{
if (Objects.equals(this.lastShipmentDays, lastShipmentDays))
{
return this;
}
else
{
return toBuilder().lastShipmentDays(lastShipmentDays).build();
}
}
public boolean isChanged()
{
return getProductPriceId() == null
|| !getPrice().isPriceListPriceUsed();
} | public boolean isMatching(@NonNull final ProductsProposalViewFilter filter)
{
return Check.isEmpty(filter.getProductName())
|| getProductName().toLowerCase().contains(filter.getProductName().toLowerCase());
}
public ProductsProposalRow withExistingOrderLine(@Nullable final OrderLine existingOrderLine)
{
if(existingOrderLine == null)
{
return this;
}
final Amount existingPrice = Amount.of(existingOrderLine.getPriceEntered(), existingOrderLine.getCurrency().getCurrencyCode());
return toBuilder()
.qty(existingOrderLine.isPackingMaterialWithInfiniteCapacity()
? existingOrderLine.getQtyEnteredCU()
: BigDecimal.valueOf(existingOrderLine.getQtyEnteredTU()))
.price(ProductProposalPrice.builder()
.priceListPrice(existingPrice)
.build())
.existingOrderLineId(existingOrderLine.getOrderLineId())
.description(existingOrderLine.getDescription())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRow.java | 1 |
请完成以下Java代码 | public void setCurrencyRate(BigDecimal CurrencyRate)
{
if (CurrencyRate == null)
{
log.warn("was NULL - set to 1");
super.setCurrencyRate(BigDecimal.ONE);
}
else if (CurrencyRate.signum() < 0)
{
log.warn("negative - " + CurrencyRate + " - set to 1");
super.setCurrencyRate(BigDecimal.ONE);
}
else
super.setCurrencyRate(CurrencyRate);
} // setCurrencyRate
/**
* Set Accounted Amounts only if not 0. Amounts overwritten in beforeSave - set conversion rate
*
* @param AmtAcctDr Dr
* @param AmtAcctCr Cr
*/
public void setAmtAcct(BigDecimal AmtAcctDr, BigDecimal AmtAcctCr)
{
// setConversion
double rateDR = 0;
if (AmtAcctDr != null && AmtAcctDr.signum() != 0)
{
rateDR = AmtAcctDr.doubleValue() / getAmtSourceDr().doubleValue();
super.setAmtAcctDr(AmtAcctDr);
}
double rateCR = 0;
if (AmtAcctCr != null && AmtAcctCr.signum() != 0)
{
rateCR = AmtAcctCr.doubleValue() / getAmtSourceCr().doubleValue(); | super.setAmtAcctCr(AmtAcctCr);
}
if (rateDR != 0 && rateCR != 0 && rateDR != rateCR)
{
log.warn("Rates Different DR=" + rateDR + "(used) <> CR=" + rateCR + "(ignored)");
rateCR = 0;
}
if (rateDR < 0 || Double.isInfinite(rateDR) || Double.isNaN(rateDR))
{
log.warn("DR Rate ignored - " + rateDR);
return;
}
if (rateCR < 0 || Double.isInfinite(rateCR) || Double.isNaN(rateCR))
{
log.warn("CR Rate ignored - " + rateCR);
return;
}
if (rateDR != 0)
setCurrencyRate(new BigDecimal(rateDR));
if (rateCR != 0)
setCurrencyRate(new BigDecimal(rateCR));
} // setAmtAcct
} // MJournalLine | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournalLine.java | 1 |
请完成以下Java代码 | private int toDigit(char hexChar) {
int digit = Character.digit(hexChar, 16);
if(digit == -1) {
throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
}
return digit;
}
public String encodeUsingBigIntegerToString(byte[] bytes) {
BigInteger bigInteger = new BigInteger(1, bytes);
return bigInteger.toString(16);
}
public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
BigInteger bigInteger = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
}
public byte[] decodeUsingBigInteger(String hexString) {
byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
if (byteArray[0] == 0) {
byte[] output = new byte[byteArray.length - 1];
System.arraycopy(byteArray, 1, output, 0, output.length);
return output;
}
return byteArray;
}
public String encodeUsingDataTypeConverter(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes);
}
public byte[] decodeUsingDataTypeConverter(String hexString) {
return DatatypeConverter.parseHexBinary(hexString);
}
public String encodeUsingApacheCommons(byte[] bytes) {
return Hex.encodeHexString(bytes);
}
public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
return Hex.decodeHex(hexString); | }
public String encodeUsingGuava(byte[] bytes) {
return BaseEncoding.base16()
.encode(bytes);
}
public byte[] decodeUsingGuava(String hexString) {
return BaseEncoding.base16()
.decode(hexString.toUpperCase());
}
public String encodeUsingHexFormat(byte[] bytes) {
HexFormat hexFormat = HexFormat.of();
return hexFormat.formatHex(bytes);
}
public byte[] decodeUsingHexFormat(String hexString) {
HexFormat hexFormat = HexFormat.of();
return hexFormat.parseHex(hexString);
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-1\src\main\java\com\baeldung\algorithms\conversion\HexStringConverter.java | 1 |
请完成以下Java代码 | default void monitor(final Runnable runnable, final Metadata metadata)
{
monitor(
() -> {
runnable.run();
return null;
},
metadata);
}
void recordElapsedTime(final long duration, TimeUnit unit, final Metadata metadata);
@Value
@Builder
class Metadata
{
@NonNull
Type type;
@NonNull
String className;
@NonNull
String functionName;
@Nullable
String windowNameAndId;
boolean isGroupingPlaceholder;
@Singular
Map<String, String> labels;
public String getFunctionNameFQ() {return className + " - " + functionName;}
}
enum Type
{ | MODEL_INTERCEPTOR("modelInterceptor"),
DOC_ACTION("docAction"),
ASYNC_WORKPACKAGE("asyncWorkPackage"),
SCHEDULER("scheduler"),
EVENTBUS_REMOTE_ENDPOINT("eventbus-remote-endpoint"),
REST_CONTROLLER("rest-controller"),
REST_CONTROLLER_WITH_WINDOW_ID("rest-controller-with-windowId"),
PO("po"),
DB("db");
Type(final String code)
{
this.code = code;
}
public boolean isAnyRestControllerType()
{
return this == Type.REST_CONTROLLER || this == Type.REST_CONTROLLER_WITH_WINDOW_ID;
}
@Getter
private final String code;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\adapter\PerformanceMonitoringService.java | 1 |
请完成以下Java代码 | public class DoublyLinkedList {
DoublyLinkedListNode head;
DoublyLinkedListNode tail;
public void add(Integer data) {
DoublyLinkedListNode newNode = new DoublyLinkedListNode(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
public static String customToString(DoublyLinkedList list) {
StringBuilder sb = new StringBuilder();
sb.append("Custom Doubly LinkedList: ");
if (list.head == null) {
sb.append("Empty List");
} else {
DoublyLinkedListNode currentNode = list.head;
while (currentNode != null) { | sb.append(currentNode.data).append(" - ");
currentNode = currentNode.next;
}
sb.delete(sb.length() - 3, sb.length());
}
return sb.toString();
}
public static void main(String[] args) {
DoublyLinkedList idsList = new DoublyLinkedList();
idsList.add(101);
idsList.add(102);
idsList.add(103);
System.out.println(customToString(idsList));
DoublyLinkedList emptyList = new DoublyLinkedList();
System.out.println(customToString(emptyList));
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-6\src\main\java\com\baeldung\listtostring\DoublyLinkedList.java | 1 |
请完成以下Java代码 | public static DeliveryRule ofNullableCode(@Nullable final String code)
{
return code != null ? ofCode(code) : null;
}
public static DeliveryRule ofCode(@NonNull final String code)
{
final DeliveryRule type = typesByCode.get(code);
if (type == null)
{
throw new AdempiereException("No " + DeliveryRule.class + " found for code: " + code);
}
return type;
}
private static final ImmutableMap<String, DeliveryRule> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), DeliveryRule::getCode);
@Nullable
public static String toCodeOrNull(@Nullable final DeliveryRule type)
{
return type != null ? type.getCode() : null;
}
public boolean isCompleteOrder()
{
return COMPLETE_ORDER.equals(this);
}
public boolean isCompleteOrderOrLine()
{
return COMPLETE_ORDER.equals(this) || COMPLETE_LINE.equals(this);
} | public boolean isBasedOnDelivery()
{
return AVAILABILITY.equals(this) || COMPLETE_ORDER.equals(this) || COMPLETE_LINE.equals(this);
}
public boolean isAvailability()
{
return AVAILABILITY.equals(this);
}
public boolean isForce()
{
return FORCE.equals(this);
}
public boolean isManual()
{
return MANUAL.equals(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\order\DeliveryRule.java | 1 |
请完成以下Java代码 | private IOException releaseInflators(IOException exceptionChain) {
Deque<Inflater> inflaterCache = this.inflaterCache;
if (inflaterCache != null) {
try {
synchronized (inflaterCache) {
inflaterCache.forEach(Inflater::end);
}
}
finally {
this.inflaterCache = null;
}
}
return exceptionChain;
}
private IOException releaseInputStreams(IOException exceptionChain) {
synchronized (this.inputStreams) {
for (InputStream inputStream : List.copyOf(this.inputStreams)) {
try {
inputStream.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
}
this.inputStreams.clear();
}
return exceptionChain;
}
private IOException releaseZipContent(IOException exceptionChain) {
ZipContent zipContent = this.zipContent;
if (zipContent != null) {
try {
zipContent.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
finally { | this.zipContent = null;
}
}
return exceptionChain;
}
private IOException releaseZipContentForManifest(IOException exceptionChain) {
ZipContent zipContentForManifest = this.zipContentForManifest;
if (zipContentForManifest != null) {
try {
zipContentForManifest.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
finally {
this.zipContentForManifest = null;
}
}
return exceptionChain;
}
private IOException addToExceptionChain(IOException exceptionChain, IOException ex) {
if (exceptionChain != null) {
exceptionChain.addSuppressed(ex);
return exceptionChain;
}
return ex;
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\NestedJarFileResources.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.