instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public Mono<Integer> add2(Mono<UserAddDTO> addDTO) {
// 插入用户记录,返回编号
Integer returnId = 1;
// 返回用户编号
return Mono.just(returnId);
}
/**
* 更新指定用户编号的用户
*
* @param updateDTO 更新用户信息 DTO
* @return 是否修改成功
*/
@PostMapping("/update")
public Mono<Boolean> update(@RequestBody Publisher<UserUpdateDTO> updateDTO) {
// 更新用户记录
Boolean success = true;
// 返回更新是否成功
return Mono.just(success); | }
/**
* 删除指定用户编号的用户
*
* @param id 用户编号
* @return 是否删除成功
*/
@PostMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE
public Mono<Boolean> delete(@RequestParam("id") Integer id) {
// 删除用户记录
Boolean success = true;
// 返回是否更新成功
return Mono.just(success);
}
} | repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-01\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java | 2 |
请完成以下Java代码 | public String getParentTaskId() {
return activiti5Task.getParentTaskId();
}
@Override
public String getTenantId() {
return activiti5Task.getTenantId();
}
@Override
public String getFormKey() {
return activiti5Task.getFormKey();
}
@Override
public Map<String, Object> getTaskLocalVariables() {
return activiti5Task.getTaskLocalVariables();
}
@Override
public Map<String, Object> getProcessVariables() {
return activiti5Task.getProcessVariables();
}
@Override
public Map<String, Object> getCaseVariables() {
return null;
}
@Override
public List<? extends IdentityLinkInfo> getIdentityLinks() {
return null;
}
@Override
public Date getClaimTime() {
return null;
}
@Override
public void setName(String name) {
activiti5Task.setName(name);
}
@Override
public void setLocalizedName(String name) {
activiti5Task.setLocalizedName(name);
}
@Override
public void setDescription(String description) {
activiti5Task.setDescription(description);
}
@Override
public void setLocalizedDescription(String description) {
activiti5Task.setLocalizedDescription(description);
}
@Override
public void setPriority(int priority) {
activiti5Task.setPriority(priority);
}
@Override
public void setOwner(String owner) { | activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) {
activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override
public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) {
activiti5Task.setCategory(category);
}
@Override
public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
}
@Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
} | repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java | 1 |
请完成以下Java代码 | public void onNew(final I_M_Product product)
{
final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig();
if (!isMSV3ServerProduct(serverConfig, product))
{
return;
}
final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID());
runAfterCommit(() -> getStockAvailabilityService().publishProductAddedEvent(productId));
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = { I_M_Product.COLUMNNAME_IsActive, I_M_Product.COLUMNNAME_M_Product_Category_ID })
public void onChange(final I_M_Product product)
{
final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig();
final I_M_Product productOld = InterfaceWrapperHelper.createOld(product, I_M_Product.class);
final boolean wasMSV3Product = isMSV3ServerProduct(serverConfig, productOld);
final boolean isMSV3Product = isMSV3ServerProduct(serverConfig, product);
if (wasMSV3Product == isMSV3Product)
{
return;
}
final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID());
if (isMSV3Product)
{
runAfterCommit(() -> getStockAvailabilityService().publishProductChangedEvent(productId));
}
else
{
runAfterCommit(() -> getStockAvailabilityService().publishProductDeletedEvent(productId));
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE)
public void onDelete(final I_M_Product product)
{
final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig();
if (!isMSV3ServerProduct(serverConfig, product))
{
return;
}
final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID());
runAfterCommit(() -> getStockAvailabilityService().publishProductDeletedEvent(productId)); | }
private boolean isMSV3ServerProduct(final MSV3ServerConfig serverConfig, final I_M_Product product)
{
if (!serverConfig.hasProducts())
{
return false;
}
if (!product.isActive())
{
return false;
}
final ProductCategoryId productCategoryId = ProductCategoryId.ofRepoId(product.getM_Product_Category_ID());
if (!serverConfig.getProductCategoryIds().contains(productCategoryId))
{
return false;
}
return true;
}
private MSV3ServerConfigService getServerConfigService()
{
return Adempiere.getBean(MSV3ServerConfigService.class);
}
private MSV3StockAvailabilityService getStockAvailabilityService()
{
return Adempiere.getBean(MSV3StockAvailabilityService.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\interceptor\M_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_EDGE;
EdgeId edgeId = edge.getId();
try {
Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(tenantId, assetId, edgeId));
logEntityActionService.logEntityAction(tenantId, assetId, savedAsset, savedAsset.getCustomerId(),
actionType, user, assetId.toString(), edgeId.toString(), edge.getName());
return savedAsset;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType,
user, e, assetId.toString(), edgeId.toString());
throw e;
}
}
@Override
public Asset unassignAssetFromEdge(TenantId tenantId, Asset asset, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; | AssetId assetId = asset.getId();
EdgeId edgeId = edge.getId();
try {
Asset savedAsset = checkNotNull(assetService.unassignAssetFromEdge(tenantId, assetId, edgeId));
logEntityActionService.logEntityAction(tenantId, assetId, asset, asset.getCustomerId(),
actionType, user, assetId.toString(), edgeId.toString(), edge.getName());
return savedAsset;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType,
user, e, assetId.toString(), edgeId.toString());
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\asset\DefaultTbAssetService.java | 2 |
请完成以下Java代码 | public void setColumnName (java.lang.String ColumnName)
{
set_Value (COLUMNNAME_ColumnName, ColumnName);
}
/** Get Spaltenname.
@return Name der Spalte in der Datenbank
*/
@Override
public java.lang.String getColumnName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ColumnName);
}
/** Set Aufsteigender.
@param IsAscending Aufsteigender */
@Override
public void setIsAscending (boolean IsAscending)
{
set_Value (COLUMNNAME_IsAscending, Boolean.valueOf(IsAscending));
}
/** Get Aufsteigender.
@return Aufsteigender */
@Override
public boolean isAscending ()
{
Object oo = get_Value(COLUMNNAME_IsAscending);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo); | }
return false;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line.java | 1 |
请完成以下Java代码 | public void setProxyPassword (java.lang.String ProxyPassword)
{
set_Value (COLUMNNAME_ProxyPassword, ProxyPassword);
}
/** Get Proxy-Passwort.
@return Password of your proxy server
*/
@Override
public java.lang.String getProxyPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProxyPassword);
}
/** Set Proxy port.
@param ProxyPort
Port of your proxy server
*/
@Override
public void setProxyPort (int ProxyPort)
{
set_Value (COLUMNNAME_ProxyPort, Integer.valueOf(ProxyPort));
}
/** Get Proxy port.
@return Port of your proxy server
*/
@Override
public int getProxyPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ProxyPort);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Require CreditCard Verification Code.
@param RequireVV
Require 3/4 digit Credit Verification Code
*/
@Override
public void setRequireVV (boolean RequireVV)
{
set_Value (COLUMNNAME_RequireVV, Boolean.valueOf(RequireVV));
}
/** Get Require CreditCard Verification Code.
@return Require 3/4 digit Credit Verification Code
*/
@Override
public boolean isRequireVV ()
{ | Object oo = get_Value(COLUMNNAME_RequireVV);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set User ID.
@param UserID
User ID or account number
*/
@Override
public void setUserID (java.lang.String UserID)
{
set_Value (COLUMNNAME_UserID, UserID);
}
/** Get User ID.
@return User ID or account number
*/
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
/** Set Vendor ID.
@param VendorID
Vendor ID for the Payment Processor
*/
@Override
public void setVendorID (java.lang.String VendorID)
{
set_Value (COLUMNNAME_VendorID, VendorID);
}
/** Get Vendor ID.
@return Vendor ID for the Payment Processor
*/
@Override
public java.lang.String getVendorID ()
{
return (java.lang.String)get_Value(COLUMNNAME_VendorID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentProcessor.java | 1 |
请完成以下Java代码 | public boolean performanceMonitoringServiceLoad(@NonNull final Callable<Boolean> callable)
{
final PerformanceMonitoringService performanceMonitoringService = performanceMonitoringService();
return performanceMonitoringService.monitor(callable, PM_METADATA_LOAD);
}
private PerformanceMonitoringService performanceMonitoringService()
{
PerformanceMonitoringService performanceMonitoringService = _performanceMonitoringService;
if (performanceMonitoringService == null || performanceMonitoringService instanceof NoopPerformanceMonitoringService)
{
performanceMonitoringService = _performanceMonitoringService = SpringContextHolder.instance.getBeanOr(
PerformanceMonitoringService.class,
NoopPerformanceMonitoringService.INSTANCE);
}
return performanceMonitoringService;
}
//
//
//
public boolean isDeveloperMode()
{
return developerModeBL().isEnabled();
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue, final int ad_client_id, final int ad_org_id)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue, ad_client_id, ad_org_id);
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue);
}
public boolean isChangeLogEnabled()
{
return sessionBL().isChangeLogEnabled();
} | public String getInsertChangeLogType(final int adClientId)
{
return sysConfigBL().getValue("SYSTEM_INSERT_CHANGELOG", "N", adClientId);
}
public void saveChangeLogs(final List<ChangeLogRecord> changeLogRecords)
{
sessionDAO().saveChangeLogs(changeLogRecords);
}
public void logMigration(final MFSession session, final PO po, final POInfo poInfo, final String actionType)
{
migrationLogger().logMigration(session, po, poInfo, actionType);
}
public void fireDocumentNoChange(final PO po, final String value)
{
documentNoBL().fireDocumentNoChange(po, value); // task 09776
}
public ADRefList getRefListById(@NonNull final ReferenceId referenceId)
{
return adReferenceService().getRefListById(referenceId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POServicesFacade.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MDCandidateDimensionFactory implements DimensionFactory<I_MD_Candidate>
{
@Override
public String getHandledTableName()
{
return I_MD_Candidate.Table_Name;
}
@Override
@NonNull
public Dimension getFromRecord(@NonNull final I_MD_Candidate record)
{
return Dimension.builder()
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.campaignId(record.getC_Campaign_ID())
.activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID()))
.salesOrderId(OrderId.ofRepoIdOrNull(record.getC_OrderSO_ID()))
.userElementString1(record.getUserElementString1())
.userElementString2(record.getUserElementString2())
.userElementString3(record.getUserElementString3())
.userElementString4(record.getUserElementString4())
.userElementString5(record.getUserElementString5())
.userElementString6(record.getUserElementString6())
.userElementString7(record.getUserElementString7()) | .build();
}
@Override
public void updateRecord(final I_MD_Candidate record, final Dimension from)
{
record.setC_Project_ID(ProjectId.toRepoId(from.getProjectId()));
record.setC_Campaign_ID(from.getCampaignId());
record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId()));
record.setC_OrderSO_ID(OrderId.toRepoId(from.getSalesOrderId()));
record.setUserElementString1(from.getUserElementString1());
record.setUserElementString2(from.getUserElementString2());
record.setUserElementString3(from.getUserElementString3());
record.setUserElementString4(from.getUserElementString4());
record.setUserElementString5(from.getUserElementString5());
record.setUserElementString6(from.getUserElementString6());
record.setUserElementString7(from.getUserElementString7());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\document\dimension\MDCandidateDimensionFactory.java | 2 |
请完成以下Java代码 | public void execute(ActivityExecution execution) {
readFields(execution);
List<String> argList = new ArrayList<String>();
argList.add(commandStr);
if (arg1Str != null)
argList.add(arg1Str);
if (arg2Str != null)
argList.add(arg2Str);
if (arg3Str != null)
argList.add(arg3Str);
if (arg4Str != null)
argList.add(arg4Str);
if (arg5Str != null)
argList.add(arg5Str);
ProcessBuilder processBuilder = new ProcessBuilder(argList);
try {
processBuilder.redirectErrorStream(redirectErrorFlag);
if (cleanEnvBoolan) {
Map<String, String> env = processBuilder.environment();
env.clear();
}
if (directoryStr != null && directoryStr.length() > 0)
processBuilder.directory(new File(directoryStr));
Process process = processBuilder.start();
if (waitFlag) {
int errorCode = process.waitFor();
if (resultVariableStr != null) {
String result = convertStreamToStr(process.getInputStream());
execution.setVariable(resultVariableStr, result);
}
if (errorCodeVariableStr != null) {
execution.setVariable(errorCodeVariableStr, Integer.toString(errorCode));
}
}
} catch (Exception e) {
throw LOG.shellExecutionException(e);
}
leave(execution);
} | public static String convertStreamToStr(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
protected String getStringFromField(Expression expression, DelegateExecution execution) {
if (expression != null) {
Object value = expression.getValue(execution);
if (value != null) {
return value.toString();
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ShellActivityBehavior.java | 1 |
请完成以下Java代码 | public void recordPlanItemInstanceOccurred(PlanItemInstanceEntity planItemInstanceEntity) {
for (CmmnHistoryManager historyManager : historyManagers) {
historyManager.recordPlanItemInstanceOccurred(planItemInstanceEntity);
}
}
@Override
public void recordPlanItemInstanceTerminated(PlanItemInstanceEntity planItemInstanceEntity) {
for (CmmnHistoryManager historyManager : historyManagers) {
historyManager.recordPlanItemInstanceTerminated(planItemInstanceEntity);
}
}
@Override
public void recordPlanItemInstanceExit(PlanItemInstanceEntity planItemInstanceEntity) {
for (CmmnHistoryManager historyManager : historyManagers) {
historyManager.recordPlanItemInstanceExit(planItemInstanceEntity);
}
}
@Override
public void updateCaseDefinitionIdInHistory(CaseDefinition caseDefinition, CaseInstanceEntity caseInstance) { | for (CmmnHistoryManager historyManager : historyManagers) {
historyManager.updateCaseDefinitionIdInHistory(caseDefinition, caseInstance);
}
}
@Override
public void recordHistoricUserTaskLogEntry(HistoricTaskLogEntryBuilder taskLogEntryBuilder) {
for (CmmnHistoryManager historyManager : historyManagers) {
historyManager.recordHistoricUserTaskLogEntry(taskLogEntryBuilder);
}
}
@Override
public void deleteHistoricUserTaskLogEntry(long logNumber) {
for (CmmnHistoryManager historyManager : historyManagers) {
historyManager.deleteHistoricUserTaskLogEntry(logNumber);
}
}
public void addHistoryManager(CmmnHistoryManager historyManager) {
historyManagers.add(historyManager);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\CompositeCmmnHistoryManager.java | 1 |
请完成以下Java代码 | public String toSqlStringWithColumnNameAlias()
{
return toSqlString() + " AS " + columnNameAlias;
}
public String toSqlString()
{
if (virtualColumnSql != null)
{
return virtualColumnSql.toSqlStringWrappedInBracketsIfNeeded();
}
else if (tableNameOrAlias != null)
{
return tableNameOrAlias + "." + columnName;
}
else
{
return columnName;
}
}
public boolean isVirtualColumn() | {
return virtualColumnSql != null;
}
public SqlSelectValue withJoinOnTableNameOrAlias(final String tableNameOrAlias)
{
return !Objects.equals(this.tableNameOrAlias, tableNameOrAlias)
? toBuilder().tableNameOrAlias(tableNameOrAlias).build()
: this;
}
public SqlSelectValue withColumnNameAlias(@NonNull final String columnNameAlias)
{
return !Objects.equals(this.columnNameAlias, columnNameAlias)
? toBuilder().columnNameAlias(columnNameAlias).build()
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlSelectValue.java | 1 |
请完成以下Java代码 | public class ApacheCommonsPropertyMutator implements PropertyMutator {
private final String propertyFileName;
public ApacheCommonsPropertyMutator(String propertyFileName) {
this.propertyFileName = propertyFileName;
}
@Override
public String getProperty(String key) throws ConfigurationException {
FileBasedConfigurationBuilder<FileBasedConfiguration> builder = getAppPropertiesConfigBuilder();
Configuration properties = builder.getConfiguration();
return (String) properties.getProperty(key);
} | @Override
public void addOrUpdateProperty(String key, String value) throws ConfigurationException {
FileBasedConfigurationBuilder<FileBasedConfiguration> builder = getAppPropertiesConfigBuilder();
Configuration configuration = builder.getConfiguration();
configuration.setProperty(key, value);
builder.save();
}
private FileBasedConfigurationBuilder<FileBasedConfiguration> getAppPropertiesConfigBuilder() {
Parameters params = new Parameters();
return new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class).configure(params.properties()
.setFileName(propertyFileName));
}
} | repos\tutorials-master\core-java-modules\core-java-properties\src\main\java\com\baeldung\core\java\properties\ApacheCommonsPropertyMutator.java | 1 |
请完成以下Java代码 | public class SendMsgJob implements Job {
@Autowired
private ISysMessageService sysMessageService;
@Autowired
private ISysBaseAPI sysBaseAPI;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info(String.format(" Jeecg-Boot 发送消息任务 SendMsgJob ! 时间:" + DateUtils.getTimestamp()));
// 1.读取消息中心数据,只查询未发送的和发送失败不超过次数的
QueryWrapper<SysMessage> queryWrapper = new QueryWrapper<SysMessage>();
queryWrapper.eq("es_send_status", SendMsgStatusEnum.WAIT.getCode())
.or(i -> i.eq("es_send_status", SendMsgStatusEnum.FAIL.getCode()).lt("es_send_num", 6));
List<SysMessage> sysMessages = sysMessageService.list(queryWrapper);
System.out.println(sysMessages);
// 2.根据不同的类型走不通的发送实现类
for (SysMessage sysMessage : sysMessages) {
// 代码逻辑说明: 模板消息发送测试调用方法修改
Integer sendNum = sysMessage.getEsSendNum();
try {
MessageDTO md = new MessageDTO();
md.setTitle(sysMessage.getEsTitle());
md.setContent(sysMessage.getEsContent());
md.setToUser(sysMessage.getEsReceiver());
md.setType(sysMessage.getEsType());
md.setToAll(false); | // 代码逻辑说明: 【QQYUN-8523】敲敲云发邮件通知,不稳定---
md.setIsTimeJob(true);
sysBaseAPI.sendTemplateMessage(md);
//发送消息成功
sysMessage.setEsSendStatus(SendMsgStatusEnum.SUCCESS.getCode());
} catch (Exception e) {
e.printStackTrace();
// 发送消息出现异常
sysMessage.setEsSendStatus(SendMsgStatusEnum.FAIL.getCode());
}
sysMessage.setEsSendNum(++sendNum);
// 发送结果回写到数据库
sysMessageService.updateById(sysMessage);
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\job\SendMsgJob.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Map<String, ConditionAndOutcomes> orderByName(Map<String, ConditionAndOutcomes> outcomes) {
MultiValueMap<String, String> map = mapToFullyQualifiedNames(outcomes.keySet());
List<String> shortNames = new ArrayList<>(map.keySet());
Collections.sort(shortNames);
Map<String, ConditionAndOutcomes> result = new LinkedHashMap<>();
for (String shortName : shortNames) {
List<String> fullyQualifiedNames = map.get(shortName);
Assert.state(fullyQualifiedNames != null, "'fullyQualifiedNames' must not be null");
if (fullyQualifiedNames.size() > 1) {
fullyQualifiedNames
.forEach((fullyQualifiedName) -> result.put(fullyQualifiedName, outcomes.get(fullyQualifiedName)));
}
else {
result.put(shortName, outcomes.get(fullyQualifiedNames.get(0)));
}
}
return result;
}
private MultiValueMap<String, String> mapToFullyQualifiedNames(Set<String> keySet) {
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
keySet
.forEach((fullyQualifiedName) -> map.add(ClassUtils.getShortName(fullyQualifiedName), fullyQualifiedName));
return map;
}
private void addMatchLogMessage(StringBuilder message, String source, ConditionAndOutcomes matches) {
message.append(String.format("%n %s matched:%n", source));
for (ConditionAndOutcome match : matches) {
logConditionAndOutcome(message, " ", match);
}
}
private void addNonMatchLogMessage(StringBuilder message, String source,
ConditionAndOutcomes conditionAndOutcomes) {
message.append(String.format("%n %s:%n", source));
List<ConditionAndOutcome> matches = new ArrayList<>();
List<ConditionAndOutcome> nonMatches = new ArrayList<>();
for (ConditionAndOutcome conditionAndOutcome : conditionAndOutcomes) {
if (conditionAndOutcome.getOutcome().isMatch()) {
matches.add(conditionAndOutcome);
}
else {
nonMatches.add(conditionAndOutcome);
}
}
message.append(String.format(" Did not match:%n"));
for (ConditionAndOutcome nonMatch : nonMatches) {
logConditionAndOutcome(message, " ", nonMatch);
}
if (!matches.isEmpty()) {
message.append(String.format(" Matched:%n"));
for (ConditionAndOutcome match : matches) {
logConditionAndOutcome(message, " ", match); | }
}
}
private void logConditionAndOutcome(StringBuilder message, String indent, ConditionAndOutcome conditionAndOutcome) {
message.append(String.format("%s- ", indent));
String outcomeMessage = conditionAndOutcome.getOutcome().getMessage();
if (StringUtils.hasLength(outcomeMessage)) {
message.append(outcomeMessage);
}
else {
message.append(conditionAndOutcome.getOutcome().isMatch() ? "matched" : "did not match");
}
message.append(" (");
message.append(ClassUtils.getShortName(conditionAndOutcome.getCondition().getClass()));
message.append(String.format(")%n"));
}
@Override
public String toString() {
return this.message.toString();
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\logging\ConditionEvaluationReportMessage.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected void doOnSuccess(UUID id) {
EntityId entityId = msgToEntityIdMap.get(id);
if (entityId != null) {
Queue<IdMsgPair<TransportProtos.ToRuleEngineMsg>> queue = entityIdToListMap.get(entityId);
if (queue != null) {
IdMsgPair<TransportProtos.ToRuleEngineMsg> next = null;
synchronized (queue) {
IdMsgPair<TransportProtos.ToRuleEngineMsg> expected = queue.peek();
if (expected != null && expected.uuid.equals(id)) {
queue.poll();
next = queue.peek();
}
}
if (next != null) {
msgConsumer.accept(next.uuid, next.msg);
}
}
} | }
private void initMaps() {
msgToEntityIdMap.clear();
entityIdToListMap.clear();
for (IdMsgPair<TransportProtos.ToRuleEngineMsg> pair : orderedMsgList) {
EntityId entityId = getEntityId(pair.msg.getValue());
if (entityId != null) {
msgToEntityIdMap.put(pair.uuid, entityId);
entityIdToListMap.computeIfAbsent(entityId, id -> new LinkedList<>()).add(pair);
}
}
}
protected abstract EntityId getEntityId(TransportProtos.ToRuleEngineMsg msg);
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\SequentialByEntityIdTbRuleEngineSubmitStrategy.java | 2 |
请完成以下Java代码 | public void setProcessInstanceIdIn(String[] processInstanceIdIn) {
this.processInstanceIdIn = processInstanceIdIn;
}
@Override
protected boolean isValidSortByValue(String value) {
return SORT_ORDER_ACTIVITY_ID.equals(value);
}
@Override
protected HistoricActivityStatisticsQuery createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createHistoricActivityStatisticsQuery(processDefinitionId);
}
@Override
protected void applyFilters(HistoricActivityStatisticsQuery query) {
if (includeCanceled != null && includeCanceled) {
query.includeCanceled();
}
if (includeFinished != null && includeFinished) {
query.includeFinished();
}
if (includeCompleteScope != null && includeCompleteScope) {
query.includeCompleteScope();
}
if (includeIncidents !=null && includeIncidents) {
query.includeIncidents();
}
if (startedAfter != null) {
query.startedAfter(startedAfter);
} | if (startedBefore != null) {
query.startedBefore(startedBefore);
}
if (finishedAfter != null) {
query.finishedAfter(finishedAfter);
}
if (finishedBefore != null) {
query.finishedBefore(finishedBefore);
}
if (processInstanceIdIn != null) {
query.processInstanceIdIn(processInstanceIdIn);
}
}
@Override
protected void applySortBy(HistoricActivityStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (SORT_ORDER_ACTIVITY_ID.equals(sortBy)) {
query.orderByActivityId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricActivityStatisticsQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AdFieldId implements RepoIdAware
{
@JsonCreator
public static AdFieldId ofRepoId(final int repoId)
{
return new AdFieldId(repoId);
}
@Nullable
public static AdFieldId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new AdFieldId(repoId) : null;
}
public static int toRepoId(@Nullable final AdFieldId id)
{
return id != null ? id.getRepoId() : -1;
} | int repoId;
private AdFieldId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Field_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\element\api\AdFieldId.java | 2 |
请完成以下Java代码 | public frame setScrolling(String scrolling)
{
addAttribute("scrolling",scrolling);
return this;
}
/**
Sets the noresize value
@param noresize true or false
*/
public frame setNoResize(boolean noresize)
{
if ( noresize == true )
addAttribute("noresize", "noresize");
else
removeAttribute("noresize");
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public frame addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public frame addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/** | Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frame addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frame addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public frame removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frame.java | 1 |
请完成以下Java代码 | public boolean applyESRMatchingBPartnerOfTheInvoice(final I_C_Invoice invoice, final I_ESR_ImportLine esrLine)
{
for (final IESRLineHandler h : handlers)
{
boolean match = h.matchBPartnerOfInvoice(invoice, esrLine);
if (!match)
{
return false;
}
}
return true;
}
@Override
public boolean applyESRMatchingBPartner(
@NonNull final I_C_BPartner bPartner, | @NonNull final I_ESR_ImportLine esrLine)
{
for (final IESRLineHandler l : handlers)
{
boolean match = l.matchBPartner(bPartner, esrLine);
if (!match)
{
return false;
}
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRLineHandlersService.java | 1 |
请完成以下Java代码 | public void setCB_Receipt_Acct (int CB_Receipt_Acct)
{
set_Value (COLUMNNAME_CB_Receipt_Acct, Integer.valueOf(CB_Receipt_Acct));
}
/** Get Cash Book Receipt.
@return Cash Book Receipts Account
*/
public int getCB_Receipt_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Receipt_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_CashBook getC_CashBook() throws RuntimeException
{
return (I_C_CashBook)MTable.get(getCtx(), I_C_CashBook.Table_Name)
.getPO(getC_CashBook_ID(), get_TrxName()); }
/** Set Cash Book. | @param C_CashBook_ID
Cash Book for recording petty cash transactions
*/
public void setC_CashBook_ID (int C_CashBook_ID)
{
if (C_CashBook_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, Integer.valueOf(C_CashBook_ID));
}
/** Get Cash Book.
@return Cash Book for recording petty cash transactions
*/
public int getC_CashBook_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CashBook_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashBook_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getNote()
{
return note;
}
public void setNote(String note)
{
this.note = note;
}
public InfoFromBuyer returnShipmentTracking(List<TrackingInfo> returnShipmentTracking)
{
this.returnShipmentTracking = returnShipmentTracking;
return this;
}
public InfoFromBuyer addReturnShipmentTrackingItem(TrackingInfo returnShipmentTrackingItem)
{
if (this.returnShipmentTracking == null)
{
this.returnShipmentTracking = new ArrayList<>();
}
this.returnShipmentTracking.add(returnShipmentTrackingItem);
return this;
}
/**
* This array shows shipment tracking information for one or more shipping packages being returned to the buyer after a payment dispute.
*
* @return returnShipmentTracking
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "This array shows shipment tracking information for one or more shipping packages being returned to the buyer after a payment dispute.")
public List<TrackingInfo> getReturnShipmentTracking()
{
return returnShipmentTracking;
}
public void setReturnShipmentTracking(List<TrackingInfo> returnShipmentTracking)
{
this.returnShipmentTracking = returnShipmentTracking;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
InfoFromBuyer infoFromBuyer = (InfoFromBuyer)o;
return Objects.equals(this.note, infoFromBuyer.note) &&
Objects.equals(this.returnShipmentTracking, infoFromBuyer.returnShipmentTracking); | }
@Override
public int hashCode()
{
return Objects.hash(note, returnShipmentTracking);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class InfoFromBuyer {\n");
sb.append(" note: ").append(toIndentedString(note)).append("\n");
sb.append(" returnShipmentTracking: ").append(toIndentedString(returnShipmentTracking)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\InfoFromBuyer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Program
{
public static final String SERIALIZED_NAME_AUTHENTICITY_VERIFICATION = "authenticityVerification";
@SerializedName(SERIALIZED_NAME_AUTHENTICITY_VERIFICATION)
private PostSaleAuthenticationProgram authenticityVerification;
public static final String SERIALIZED_NAME_FULFILLMENT_PROGRAM = "fulfillmentProgram";
@SerializedName(SERIALIZED_NAME_FULFILLMENT_PROGRAM)
private EbayFulfillmentProgram fulfillmentProgram;
public Program authenticityVerification(PostSaleAuthenticationProgram authenticityVerification)
{
this.authenticityVerification = authenticityVerification;
return this;
}
/**
* Get authenticityVerification
*
* @return authenticityVerification
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public PostSaleAuthenticationProgram getAuthenticityVerification()
{
return authenticityVerification;
}
public void setAuthenticityVerification(PostSaleAuthenticationProgram authenticityVerification)
{
this.authenticityVerification = authenticityVerification;
}
public Program fulfillmentProgram(EbayFulfillmentProgram fulfillmentProgram)
{
this.fulfillmentProgram = fulfillmentProgram;
return this;
}
/**
* Get fulfillmentProgram
*
* @return fulfillmentProgram
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public EbayFulfillmentProgram getFulfillmentProgram()
{
return fulfillmentProgram;
}
public void setFulfillmentProgram(EbayFulfillmentProgram fulfillmentProgram)
{
this.fulfillmentProgram = fulfillmentProgram;
}
@Override
public boolean equals(Object o)
{ | if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Program program = (Program)o;
return Objects.equals(this.authenticityVerification, program.authenticityVerification) &&
Objects.equals(this.fulfillmentProgram, program.fulfillmentProgram);
}
@Override
public int hashCode()
{
return Objects.hash(authenticityVerification, fulfillmentProgram);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class Program {\n");
sb.append(" authenticityVerification: ").append(toIndentedString(authenticityVerification)).append("\n");
sb.append(" fulfillmentProgram: ").append(toIndentedString(fulfillmentProgram)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Program.java | 2 |
请完成以下Java代码 | public <T extends BusinessCaseDetail> T getBusinessCaseDetailNotNull(@NonNull final Class<T> type)
{
if (type.isInstance(businessCaseDetail))
{
return type.cast(businessCaseDetail);
}
else
{
throw new AdempiereException("businessCaseDetail is not matching " + type.getSimpleName() + ": " + this);
}
}
public <T extends BusinessCaseDetail> Candidate withBusinessCaseDetail(@NonNull final Class<T> type, @NonNull final UnaryOperator<T> mapper)
{
final T businessCaseDetail = getBusinessCaseDetailNotNull(type);
final T businessCaseDetailChanged = mapper.apply(businessCaseDetail);
if (Objects.equals(businessCaseDetail, businessCaseDetailChanged))
{
return this;
}
return withBusinessCaseDetail(businessCaseDetailChanged);
}
@Nullable
public String getTraceId()
{
final DemandDetail demandDetail = getDemandDetail();
return demandDetail != null ? demandDetail.getTraceId() : null;
}
/**
* This is enabled by the current usage of {@link #parentId} | */
public boolean isStockCandidateOfThisCandidate(@NonNull final Candidate potentialStockCandidate)
{
if (potentialStockCandidate.type != CandidateType.STOCK)
{
return false;
}
switch (type)
{
case DEMAND:
return potentialStockCandidate.getParentId().equals(id);
case SUPPLY:
return potentialStockCandidate.getId().equals(parentId);
default:
return false;
}
}
/**
* The qty is always stored as an absolute value on the candidate, but we're interested if the candidate is adding or subtracting qty to the stock.
*/
public BigDecimal getStockImpactPlannedQuantity()
{
switch (getType())
{
case DEMAND:
case UNEXPECTED_DECREASE:
case INVENTORY_DOWN:
return getQuantity().negate();
default:
return getQuantity();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\Candidate.java | 1 |
请完成以下Java代码 | public TableOrgPermissions.Builder asNewBuilder()
{
final TableOrgPermissions.Builder builder = builder();
builder.addPermissions(this, PermissionsBuilder.CollisionPolicy.Override);
return builder;
}
@Override
protected TableOrgPermission noPermission() {return null;}
public Optional<Set<OrgId>> getOrgsWithAccess(@Nullable final String tableName, @NonNull final Access access)
{
// Does not apply if table name is not provided
if (tableName == null || Check.isBlank(tableName))
{
return Optional.empty();
}
final ImmutableList<TableOrgPermission> tablePermissions = permissionsByTableName.get(tableName);
if (tablePermissions.isEmpty())
{
return Optional.empty();
} | final ImmutableSet<OrgId> orgIds = tablePermissions.stream()
.filter(permission -> permission.hasAccess(access))
.map(TableOrgPermission::getOrgId)
.collect(ImmutableSet.toImmutableSet());
return Optional.of(orgIds);
}
public static class Builder extends PermissionsBuilder<TableOrgPermission, TableOrgPermissions>
{
@Override
protected TableOrgPermissions createPermissionsInstance()
{
return new TableOrgPermissions(this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableOrgPermissions.java | 1 |
请完成以下Java代码 | public int getTimeSlotInHours()
{
if (isTimeSlot())
{
return (int)Duration.between(timeSlotStart, timeSlotEnd).toHours();
}
else
{
return 24;
}
}
public boolean isAvailable()
{
return isActive()
&& getAvailableDaysPerWeek() > 0
&& getTimeSlotInHours() > 0;
}
public boolean isDayAvailable(final Instant date)
{
return isActive()
&& isDayAvailable(date.atZone(SystemTime.zoneId()).getDayOfWeek());
}
public int getAvailableDaysPerWeek()
{
return availableDaysOfWeek.size();
}
public boolean isDayAvailable(@NonNull final DayOfWeek dayOfWeek)
{
return availableDaysOfWeek.contains(dayOfWeek);
}
@Deprecated
public Timestamp getDayStart(final Timestamp date)
{
final Instant dayStart = getDayStart(date.toInstant());
return Timestamp.from(dayStart);
}
public Instant getDayStart(@NonNull final Instant date)
{
return getDayStart(date.atZone(SystemTime.zoneId())).toInstant();
}
public LocalDateTime getDayStart(final LocalDateTime date)
{
return getDayStart(date.atZone(SystemTime.zoneId())).toLocalDateTime();
}
public ZonedDateTime getDayStart(final ZonedDateTime date)
{
if (isTimeSlot())
{
return date.toLocalDate().atTime(getTimeSlotStart()).atZone(date.getZone());
}
else
{
return date.toLocalDate().atStartOfDay().atZone(date.getZone());
}
} | @Deprecated
public Timestamp getDayEnd(final Timestamp date)
{
final LocalDateTime dayEnd = getDayEnd(TimeUtil.asLocalDateTime(date));
return TimeUtil.asTimestamp(dayEnd);
}
public Instant getDayEnd(final Instant date)
{
return getDayEnd(date.atZone(SystemTime.zoneId())).toInstant();
}
public LocalDateTime getDayEnd(final LocalDateTime date)
{
return getDayEnd(date.atZone(SystemTime.zoneId())).toLocalDateTime();
}
public ZonedDateTime getDayEnd(final ZonedDateTime date)
{
if (isTimeSlot())
{
return date.toLocalDate().atTime(timeSlotEnd).atZone(date.getZone());
}
else
{
return date.toLocalDate().atTime(LocalTime.MAX).atZone(date.getZone());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ResourceType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args).close();
}
/*
* Boot will autowire this into the container factory.
*/
@Bean
public CommonErrorHandler errorHandler(KafkaOperations<Object, Object> template) {
return new DefaultErrorHandler(
new DeadLetterPublishingRecoverer(template), new FixedBackOff(1000L, 2));
}
@Bean
public RecordMessageConverter converter() {
JsonMessageConverter converter = new JsonMessageConverter();
DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper();
typeMapper.setTypePrecedence(TypePrecedence.TYPE_ID);
typeMapper.addTrustedPackages("com.common");
Map<String, Class<?>> mappings = new HashMap<>();
mappings.put("foo", Foo2.class);
mappings.put("bar", Bar2.class);
typeMapper.setIdClassMapping(mappings);
converter.setTypeMapper(typeMapper); | return converter;
}
@Bean
public NewTopic foos() {
return new NewTopic("foos", 1, (short) 1);
}
@Bean
public NewTopic bars() {
return new NewTopic("bars", 1, (short) 1);
}
@Bean
@Profile("default") // Don't run from test(s)
public ApplicationRunner runner() {
return args -> {
System.out.println("Hit Enter to terminate...");
System.in.read();
};
}
} | repos\spring-kafka-main\samples\sample-02\src\main\java\com\example\Application.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public MedicineWriter medicineWriter(@Value("#{jobParameters}") Map<String, Object> jobParameters) {
MedicineWriter medicineWriter = new MedicineWriter();
enrichWithJobParameters(jobParameters, medicineWriter);
return medicineWriter;
}
@Bean
public Job medExpirationJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, MedicineWriter medicineWriter, MedicineProcessor medicineProcessor, ExpiresSoonMedicineReader expiresSoonMedicineReader) {
Step notifyAboutExpiringMedicine = new StepBuilder("notifyAboutExpiringMedicine", jobRepository).<Medicine, Medicine>chunk(10)
.reader(expiresSoonMedicineReader)
.processor(medicineProcessor)
.writer(medicineWriter)
.faultTolerant()
.transactionManager(transactionManager)
.build();
return new JobBuilder("medExpirationJob", jobRepository).incrementer(new RunIdIncrementer()) | .start(notifyAboutExpiringMedicine)
.build();
}
private void enrichWithJobParameters(Map<String, Object> jobParameters, ContainsJobParameters container) {
if (jobParameters.get(BatchConstants.TRIGGERED_DATE_TIME) != null) {
container.setTriggeredDateTime(ZonedDateTime.parse(jobParameters.get(BatchConstants.TRIGGERED_DATE_TIME)
.toString()));
}
if (jobParameters.get(BatchConstants.TRACE_ID) != null) {
container.setTraceId(jobParameters.get(BatchConstants.TRACE_ID)
.toString());
}
}
} | repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchreaderproperties\BatchConfiguration.java | 2 |
请完成以下Java代码 | void sendToRequestTemplate(Request request, UUID requestId, Integer partition, SettableFuture<Response> future, ResponseMetaData<Response> responseMetaData) {
log.trace("[{}] Sending request, key [{}], expTime [{}], request {}", requestId, request.getKey(), responseMetaData.expTime, request);
if (messagesStats != null) {
messagesStats.incrementTotal();
}
TopicPartitionInfo tpi = TopicPartitionInfo.builder()
.topic(requestTemplate.getDefaultTopic())
.partition(partition)
.build();
requestTemplate.send(tpi, request, new TbQueueCallback() {
@Override
public void onSuccess(TbQueueMsgMetadata metadata) {
if (messagesStats != null) {
messagesStats.incrementSuccessful();
}
log.trace("[{}] Request sent: {}, request {}", requestId, metadata, request);
}
@Override
public void onFailure(Throwable t) {
if (messagesStats != null) {
messagesStats.incrementFailed();
}
pendingRequests.remove(requestId);
future.setException(t);
}
});
}
@Getter
static class ResponseMetaData<T> {
private final long submitTime; | private final long timeout;
private final long expTime;
private final SettableFuture<T> future;
ResponseMetaData(long ts, SettableFuture<T> future, long submitTime, long timeout) {
this.submitTime = submitTime;
this.timeout = timeout;
this.expTime = ts;
this.future = future;
}
@Override
public String toString() {
return "ResponseMetaData{" +
"submitTime=" + submitTime +
", calculatedExpTime=" + (submitTime + timeout) +
", deltaMs=" + (expTime - submitTime) +
", expTime=" + expTime +
", future=" + future +
'}';
}
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\DefaultTbQueueRequestTemplate.java | 1 |
请完成以下Java代码 | public boolean isNew(final Object model)
{
return POJOWrapper.isNew(model);
}
@Override
public <T> T getValue(final Object model, final String columnName, final boolean throwExIfColumnNotFound, final boolean useOverrideColumnIfAvailable)
{
final POJOWrapper wrapper = POJOWrapper.getWrapper(model);
if (useOverrideColumnIfAvailable)
{
final IModelInternalAccessor modelAccessor = wrapper.getModelInternalAccessor();
final T value = getValueOverrideOrNull(modelAccessor, columnName);
if (value != null)
{
return value;
}
}
//
if (!wrapper.hasColumnName(columnName))
{
if (throwExIfColumnNotFound)
{
throw new AdempiereException("No columnName " + columnName + " found for " + model);
}
else
{
return null;
}
}
@SuppressWarnings("unchecked")
final T value = (T)wrapper.getValuesMap().get(columnName);
return value;
}
@Override
public boolean isValueChanged(final Object model, final String columnName)
{
return POJOWrapper.isValueChanged(model, columnName);
}
@Override
public boolean isValueChanged(final Object model, final Set<String> columnNames)
{
return POJOWrapper.isValueChanged(model, columnNames);
}
@Override
public boolean isNull(final Object model, final String columnName)
{
return POJOWrapper.isNull(model, columnName);
} | @Override
public <T> T getDynAttribute(final Object model, final String attributeName)
{
final T value = POJOWrapper.getDynAttribute(model, attributeName);
return value;
}
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return POJOWrapper.setDynAttribute(model, attributeName, value);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
throw new UnsupportedOperationException("Getting PO from '" + model + "' is not supported in JUnit testing mode");
}
@Override
public Evaluatee getEvaluatee(final Object model)
{
return POJOWrapper.getWrapper(model).asEvaluatee();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOInterfaceWrapperHelper.java | 1 |
请完成以下Java代码 | public void setUrl(String url) {
this.url = url;
}
public @Nullable String getMethod() {
return this.method;
}
@NullUnmarked
public void setMethod(String method) {
this.method = (method != null) ? method.toUpperCase(Locale.ENGLISH) : null;
}
private SecurityContext getContext() {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
String[] names = appContext.getBeanNamesForType(SecurityContextHolderStrategy.class);
if (names.length == 1) {
SecurityContextHolderStrategy strategy = appContext.getBean(SecurityContextHolderStrategy.class);
return strategy.getContext();
}
return SecurityContextHolder.getContext();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, SecurityExpressionHandler> handlers = appContext.getBeansOfType(SecurityExpressionHandler.class);
for (SecurityExpressionHandler handler : handlers.values()) {
if (FilterInvocation.class
.equals(GenericTypeResolver.resolveTypeArgument(handler.getClass(), SecurityExpressionHandler.class))) {
return handler;
}
} | throw new IOException("No visible WebSecurityExpressionHandler instance could be found in the application "
+ "context. There must be at least one in order to support expressions in JSP 'authorize' tags.");
}
private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException {
WebInvocationPrivilegeEvaluator privEvaluatorFromRequest = (WebInvocationPrivilegeEvaluator) getRequest()
.getAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE);
if (privEvaluatorFromRequest != null) {
return privEvaluatorFromRequest;
}
ApplicationContext ctx = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
if (wipes.isEmpty()) {
throw new IOException(
"No visible WebInvocationPrivilegeEvaluator instance could be found in the application "
+ "context. There must be at least one in order to support the use of URL access checks in 'authorize' tags.");
}
return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0];
}
} | repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTag.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Customer save(Customer customer, SecurityUser user) throws Exception {
return save(customer, NameConflictStrategy.DEFAULT, user);
}
@Override
public Customer save(Customer customer, NameConflictStrategy nameConflictStrategy, SecurityUser user) throws Exception {
ActionType actionType = customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = customer.getTenantId();
try {
Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer, nameConflictStrategy));
autoCommit(user, savedCustomer.getId());
logEntityActionService.logEntityAction(tenantId, savedCustomer.getId(), savedCustomer, null, actionType, user);
return savedCustomer;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.CUSTOMER), customer, actionType, user, e);
throw e;
}
}
@Override | public void delete(Customer customer, User user) {
ActionType actionType = ActionType.DELETED;
TenantId tenantId = customer.getTenantId();
CustomerId customerId = customer.getId();
try {
customerService.deleteCustomer(tenantId, customerId);
logEntityActionService.logEntityAction(tenantId, customer.getId(), customer, customerId, actionType,
user, customerId.toString());
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.CUSTOMER), actionType, user,
e, customerId.toString());
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\customer\DefaultTbCustomerService.java | 2 |
请完成以下Java代码 | public static <T> Result error(String msg) {
Result<T> result = new Result<>();
result.setCode("500");
result.setStatus(Status.ERROR);
result.setMessage(msg);
return result;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status; | }
public static enum Status {
SUCCESS("OK"),
ERROR("ERROR");
private String code;
private Status(String code) {
this.code = code;
}
public String code() {
return this.code;
}
}
} | repos\spring-boot-student-master\spring-boot-student-hystrix\src\main\java\com\xiaolyuh\entity\Result.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class ReceiveFrom
{
@NonNull String lineId;
@NonNull BigDecimal qtyReceived;
@Nullable String bestBeforeDate;
@Nullable String productionDate;
@Nullable String lotNo;
@Nullable BigDecimal catchWeight;
@Nullable String catchWeightUomSymbol;
@Nullable ScannedCode barcode;
@Nullable JsonLUReceivingTarget aggregateToLU;
@Nullable JsonTUReceivingTarget aggregateToTU;
@JsonIgnore
public FinishedGoodsReceiveLineId getFinishedGoodsReceiveLineId() {return FinishedGoodsReceiveLineId.ofString(lineId);}
}
@Nullable ReceiveFrom receiveFrom;
@Value
@Builder
@Jacksonized
public static class PickTo
{
@NonNull String wfProcessId;
@NonNull String activityId;
@NonNull String lineId;
}
@Nullable PickTo pickTo;
@Builder
@Jacksonized
private JsonManufacturingOrderEvent(
@NonNull final String wfProcessId,
@NonNull final String wfActivityId, | //
@Nullable final IssueTo issueTo,
@Nullable final ReceiveFrom receiveFrom,
@Nullable final PickTo pickTo)
{
if (CoalesceUtil.countNotNulls(issueTo, receiveFrom) != 1)
{
throw new AdempiereException("One and only one action like issueTo, receiveFrom etc shall be specified in an event.");
}
this.wfProcessId = wfProcessId;
this.wfActivityId = wfActivityId;
this.issueTo = issueTo;
this.receiveFrom = receiveFrom;
this.pickTo = pickTo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\rest_api\json\JsonManufacturingOrderEvent.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setUrlAccessDecisionManager(UrlAccessDecisionManager urlAccessDecisionManager) {
super.setAccessDecisionManager(urlAccessDecisionManager);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
public void invoke(FilterInvocation fi) throws IOException, ServletException {
//fi里面有一个被拦截的url
//里面调用UrlMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
//再调用UrlAccessDecisionManager的decide方法来校验用户的权限是否足够
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
//执行下一个拦截器
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null); | }
}
@Override
public void destroy() {
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
} | repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\security\UrlFilterSecurityInterceptor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
return Objects.hash(countryCode, number);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class Phone {\n");
sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n");
sb.append(" number: ").append(toIndentedString(number)).append("\n");
sb.append("}");
return sb.toString();
} | /**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Phone.java | 2 |
请完成以下Java代码 | public param setType(String cdata)
{
addAttribute("type",cdata);
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public param addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public param addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
} | /**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public param addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public param addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public param removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\param.java | 1 |
请完成以下Java代码 | private GenericZoomIntoTableWindow retrieveTableWindow(final ResultSet rs) throws SQLException
{
return GenericZoomIntoTableWindow.builder()
.priority(rs.getInt("priority"))
.adWindowId(AdWindowId.ofRepoId(rs.getInt("AD_Window_ID")))
.isDefaultSOWindow(StringUtils.toBoolean(rs.getString("IsDefaultSOWindow")))
.isDefaultPOWindow(StringUtils.toBoolean(rs.getString("IsDefaultPOWindow")))
.tabSqlWhereClause(StringUtils.trimBlankToNull(rs.getString("tab_whereClause")))
.build();
}
@Value
@Builder
private static class ParentLink
{
@NonNull String linkColumnName;
@NonNull String parentTableName;
}
@Nullable
private ParentLink getParentLink_HeaderForLine(@NonNull final POInfo poInfo)
{
final String tableName = poInfo.getTableName();
if (!tableName.endsWith("Line"))
{
return null;
}
final String parentTableName = tableName.substring(0, tableName.length() - "Line".length());
final String parentLinkColumnName = parentTableName + "_ID";
if (!poInfo.hasColumnName(parentLinkColumnName))
{
return null;
}
// virtual column parent link is not supported
if (poInfo.isVirtualColumn(parentLinkColumnName))
{
return null; | }
return ParentLink.builder()
.linkColumnName(parentLinkColumnName)
.parentTableName(parentTableName)
.build();
}
@Nullable
private ParentLink getParentLink_SingleParentColumn(@NonNull final POInfo poInfo)
{
final String parentLinkColumnName = poInfo.getSingleParentColumnName().orElse(null);
if (parentLinkColumnName == null)
{
return null;
}
// virtual column parent link is not supported
if (poInfo.isVirtualColumn(parentLinkColumnName))
{
return null;
}
final String parentTableName = poInfo.getReferencedTableNameOrNull(parentLinkColumnName);
if (parentTableName == null)
{
return null;
}
return ParentLink.builder()
.linkColumnName(parentLinkColumnName)
.parentTableName(parentTableName)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\DefaultGenericZoomIntoTableInfoRepository.java | 1 |
请完成以下Java代码 | public void launchTask(ExecutorDriver driver, TaskInfo task) {
Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
.setState(Protos.TaskState.TASK_RUNNING).build();
driver.sendStatusUpdate(status);
String myStatus = "Hello Framework";
driver.sendFrameworkMessage(myStatus.getBytes());
System.out.println("Hello World!!!");
status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
.setState(Protos.TaskState.TASK_FINISHED).build();
driver.sendStatusUpdate(status);
}
@Override
public void killTask(ExecutorDriver driver, Protos.TaskID taskId) {
} | @Override
public void frameworkMessage(ExecutorDriver driver, byte[] data) {
}
@Override
public void shutdown(ExecutorDriver driver) {
}
@Override
public void error(ExecutorDriver driver, String message) {
}
public static void main(String[] args) {
MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor());
System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1);
}
} | repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\mesos\executors\HelloWorldExecutor.java | 1 |
请完成以下Java代码 | public void setMultiplier(double multiplier) {
super.setMultiplier(multiplier);
calculateMaxElapsed();
}
@Override
public void setMaxInterval(long maxInterval) {
super.setMaxInterval(maxInterval);
calculateMaxElapsed();
}
@Override
public void setMaxElapsedTime(long maxElapsedTime) {
throw new IllegalStateException("'maxElapsedTime' is calculated from the 'maxRetries' property");
} | @SuppressWarnings("this-escape")
private void calculateMaxElapsed() {
long maxInterval = getMaxInterval();
long maxElapsed = Math.min(getInitialInterval(), maxInterval);
long current = maxElapsed;
for (int i = 1; i < this.maxRetries; i++) {
long next = Math.min((long) (current * getMultiplier()), maxInterval);
current = next;
maxElapsed += current;
}
super.setMaxElapsedTime(maxElapsed);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\ExponentialBackOffWithMaxRetries.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public String getOperator() {
if (operator != null) {
return operator.toString();
}
return QueryOperator.EQUALS.toString();
}
public String getTextValue() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getTextValue();
}
return null;
}
public Long getLongValue() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getLongValue();
}
return null;
}
public Double getDoubleValue() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getDoubleValue();
}
return null;
} | public String getTextValue2() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getTextValue2();
}
return null;
}
public String getType() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getType().getTypeName();
}
return null;
}
public boolean isLocal() {
return local;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\QueryVariableValue.java | 1 |
请完成以下Java代码 | public final Object getValue(Bindings bindings, ELContext context, Class<?> type) {
Object value = eval(bindings, context);
if (type != null) {
value = bindings.convert(value, type);
}
return value;
}
public abstract void appendStructure(StringBuilder builder, Bindings bindings);
public abstract Object eval(Bindings bindings, ELContext context);
public final String getStructuralId(Bindings bindings) {
StringBuilder builder = new StringBuilder();
appendStructure(builder, bindings);
return builder.toString();
}
/**
* Find accessible method. Searches the inheritance tree of the class declaring
* the method until it finds a method that can be invoked.
* @param method method
* @return accessible method or <code>null</code>
*/
private static Method findPublicAccessibleMethod(Method method) {
if (method == null || !Modifier.isPublic(method.getModifiers())) {
return null;
}
if (method.isAccessible() || Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
return method;
}
for (Class<?> cls : method.getDeclaringClass().getInterfaces()) {
Method mth = null;
try {
mth = findPublicAccessibleMethod(cls.getMethod(method.getName(), method.getParameterTypes()));
if (mth != null) {
return mth;
}
} catch (NoSuchMethodException ignore) {
// do nothing
}
}
Class<?> cls = method.getDeclaringClass().getSuperclass();
if (cls != null) {
Method mth = null;
try {
mth = findPublicAccessibleMethod(cls.getMethod(method.getName(), method.getParameterTypes()));
if (mth != null) { | return mth;
}
} catch (NoSuchMethodException ignore) {
// do nothing
}
}
return null;
}
protected Method findAccessibleMethod(Method method) {
Method result = findPublicAccessibleMethod(method);
if (result == null && method != null && Modifier.isPublic(method.getModifiers())) {
result = method;
try {
method.setAccessible(true);
} catch (SecurityException e) {
result = null;
}
}
return result;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstNode.java | 1 |
请完成以下Java代码 | public ProcessEngineConfiguration setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
return this;
}
public String getXmlEncoding() {
return xmlEncoding;
}
public ProcessEngineConfiguration setXmlEncoding(String xmlEncoding) {
this.xmlEncoding = xmlEncoding;
return this;
}
public Clock getClock() {
return clock;
}
public ProcessEngineConfiguration setClock(Clock clock) {
this.clock = clock;
return this;
}
public ProcessDiagramGenerator getProcessDiagramGenerator() {
return this.processDiagramGenerator;
}
public ProcessEngineConfiguration setProcessDiagramGenerator(ProcessDiagramGenerator processDiagramGenerator) {
this.processDiagramGenerator = processDiagramGenerator;
return this;
}
public AsyncExecutor getAsyncExecutor() {
return asyncExecutor;
}
public ProcessEngineConfiguration setAsyncExecutor(AsyncExecutor asyncExecutor) {
this.asyncExecutor = asyncExecutor;
return this;
}
public int getLockTimeAsyncJobWaitTime() {
return lockTimeAsyncJobWaitTime;
}
public ProcessEngineConfiguration setLockTimeAsyncJobWaitTime(int lockTimeAsyncJobWaitTime) {
this.lockTimeAsyncJobWaitTime = lockTimeAsyncJobWaitTime; | return this;
}
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 List<JobProcessor> getJobProcessors() {
return jobProcessors;
}
public ProcessEngineConfiguration setJobProcessors(List<JobProcessor> jobProcessors) {
this.jobProcessors = jobProcessors;
return this;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java | 1 |
请完成以下Java代码 | public Map<String, VariableInstance> execute(CommandContext commandContext) {
if (taskId == null) {
throw new ActivitiIllegalArgumentException("taskId is null");
}
TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
if (task == null) {
throw new ActivitiObjectNotFoundException("task " + taskId + " doesn't exist", Task.class);
}
Map<String, VariableInstance> variables = null;
if (variableNames == null) {
if (isLocal) {
variables = task.getVariableInstancesLocal();
} else {
variables = task.getVariableInstances();
}
} else { | if (isLocal) {
variables = task.getVariableInstancesLocal(variableNames, false);
} else {
variables = task.getVariableInstances(variableNames, false);
}
}
if (variables != null) {
for (Entry<String, VariableInstance> entry : variables.entrySet()) {
if (entry.getValue() != null) {
entry.getValue().getValue();
}
}
}
return variables;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetTaskVariableInstancesCmd.java | 1 |
请完成以下Java代码 | public void registerHints(RuntimeHints hints, ConfigurableListableBeanFactory beanFactory) {
List<Class<?>> toProxy = new ArrayList<>();
for (Class<?> clazz : this.classesToProxy) {
toProxy.add(clazz);
traverseType(toProxy, clazz);
}
for (Class<?> clazz : toProxy) {
registerProxy(hints, clazz);
}
}
private void registerProxy(RuntimeHints hints, Class<?> clazz) {
Class<?> proxied = this.proxyFactory.proxy(clazz);
if (proxied == null) {
return;
}
if (Proxy.isProxyClass(proxied)) {
hints.proxies().registerJdkProxy(proxied.getInterfaces());
return;
}
if (SpringProxy.class.isAssignableFrom(proxied)) {
hints.reflection()
.registerType(clazz, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS)
.registerType(proxied, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.ACCESS_DECLARED_FIELDS);
}
} | private void traverseType(List<Class<?>> toProxy, Class<?> clazz) {
if (clazz == Object.class || this.visitedClasses.contains(clazz)) {
return;
}
this.visitedClasses.add(clazz);
for (Method m : clazz.getDeclaredMethods()) {
AuthorizeReturnObject object = this.scanner.scan(m, clazz);
if (object == null) {
continue;
}
Class<?> returnType = m.getReturnType();
toProxy.add(returnType);
traverseType(toProxy, returnType);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\aot\hint\AuthorizeReturnObjectHintsRegistrar.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UsersApi {
private UserRepository userRepository;
private UserQueryService userQueryService;
private PasswordEncoder passwordEncoder;
private JwtService jwtService;
private UserService userService;
@RequestMapping(path = "/users", method = POST)
public ResponseEntity createUser(@Valid @RequestBody RegisterParam registerParam) {
User user = userService.createUser(registerParam);
UserData userData = userQueryService.findById(user.getId()).get();
return ResponseEntity.status(201)
.body(userResponse(new UserWithToken(userData, jwtService.toToken(user))));
}
@RequestMapping(path = "/users/login", method = POST)
public ResponseEntity userLogin(@Valid @RequestBody LoginParam loginParam) {
Optional<User> optional = userRepository.findByEmail(loginParam.getEmail());
if (optional.isPresent()
&& passwordEncoder.matches(loginParam.getPassword(), optional.get().getPassword())) {
UserData userData = userQueryService.findById(optional.get().getId()).get();
return ResponseEntity.ok(
userResponse(new UserWithToken(userData, jwtService.toToken(optional.get()))));
} else {
throw new InvalidAuthenticationException();
}
}
private Map<String, Object> userResponse(UserWithToken userWithToken) {
return new HashMap<String, Object>() {
{ | put("user", userWithToken);
}
};
}
}
@Getter
@JsonRootName("user")
@NoArgsConstructor
class LoginParam {
@NotBlank(message = "can't be empty")
@Email(message = "should be an email")
private String email;
@NotBlank(message = "can't be empty")
private String password;
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\UsersApi.java | 2 |
请完成以下Java代码 | public void onSetSavepoint(final ITrx trx, final ITrxSavepoint savepoint)
{
final ITrxConstraints constraints = getConstraints();
if (Services.get(ITrxConstraintsBL.class).isDisabled(constraints))
{
return; // nothing to do
}
if (constraints.isActive())
{
if (constraints.getMaxSavepoints() < getSavepointsForTrxName(trx.getTrxName()).size())
{
throw new TrxConstraintException("Transaction '" +
trx + "' has too many unreleased savepoints: " + getSavepointsForTrxName(trx.getTrxName()));
}
}
}
@Override
public void onReleaseSavepoint(final ITrx trx, final ITrxSavepoint savepoint)
{
getSavepointsForTrxName(trx.getTrxName()).remove(savepoint);
}
private static ITrxConstraints getConstraints()
{
return Services.get(ITrxConstraintsBL.class).getConstraints();
}
private Collection<String> getTrxNamesForCurrentThread()
{
return getTrxNamesForThreadId(Thread.currentThread().getId());
}
private Collection<String> getTrxNamesForThreadId(final long threadId)
{
synchronized (threadId2TrxName)
{
Collection<String> trxNames = threadId2TrxName.get(threadId);
if (trxNames == null)
{
trxNames = new HashSet<String>();
threadId2TrxName.put(threadId, trxNames);
}
return trxNames;
}
}
private Collection<ITrxSavepoint> getSavepointsForTrxName(final String trxName)
{
synchronized (trxName2SavePoint)
{ | Collection<ITrxSavepoint> savepoints = trxName2SavePoint.get(trxName);
if (savepoints == null)
{
savepoints = new HashSet<ITrxSavepoint>();
trxName2SavePoint.put(trxName, savepoints);
}
return savepoints;
}
}
private String mkStacktraceInfo(final Thread thread, final String beginStacktrace)
{
final StringBuilder msgSB = new StringBuilder();
msgSB.append(">>> Stacktrace at trx creation, commit or rollback:\n");
msgSB.append(beginStacktrace);
msgSB.append(">>> Current stacktrace of the creating thread:\n");
if (thread.isAlive())
{
msgSB.append(mkStacktrace(thread));
}
else
{
msgSB.append("\t(Thread already finished)\n");
}
final String msg = msgSB.toString();
return msg;
}
@Override
public String getCreationStackTrace(final String trxName)
{
return trxName2Stacktrace.get(trxName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\OpenTrxBL.java | 1 |
请完成以下Java代码 | public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return key;
}
public String getUsername() {
return value;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
} | public Map<String, String> getDetails() {
return details;
}
public void setDetails(Map<String, String> details) {
this.details = details;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", type=" + type
+ ", userId=" + userId
+ ", key=" + key
+ ", value=" + value
+ ", password=" + password
+ ", parentId=" + parentId
+ ", details=" + details
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityInfoEntity.java | 1 |
请完成以下Java代码 | public String getPhneNb() {
return phneNb;
}
/**
* Sets the value of the phneNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPhneNb(String value) {
this.phneNb = value;
}
/**
* Gets the value of the mobNb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMobNb() {
return mobNb;
}
/**
* Sets the value of the mobNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMobNb(String value) {
this.mobNb = value;
}
/**
* Gets the value of the faxNb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFaxNb() {
return faxNb;
}
/**
* Sets the value of the faxNb property.
*
* @param value
* allowed object is | * {@link String }
*
*/
public void setFaxNb(String value) {
this.faxNb = value;
}
/**
* Gets the value of the emailAdr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEmailAdr() {
return emailAdr;
}
/**
* Sets the value of the emailAdr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmailAdr(String value) {
this.emailAdr = value;
}
/**
* Gets the value of the othr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOthr() {
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOthr(String value) {
this.othr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ContactDetails2.java | 1 |
请完成以下Java代码 | public String getMeta_Publisher ()
{
return (String)get_Value(COLUMNNAME_Meta_Publisher);
}
/** Set Meta RobotsTag.
@param Meta_RobotsTag
RobotsTag defines how search robots should handle this content
*/
public void setMeta_RobotsTag (String Meta_RobotsTag)
{
set_Value (COLUMNNAME_Meta_RobotsTag, Meta_RobotsTag);
}
/** Get Meta RobotsTag.
@return RobotsTag defines how search robots should handle this content
*/
public String getMeta_RobotsTag ()
{
return (String)get_Value(COLUMNNAME_Meta_RobotsTag);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name); | }
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject.java | 1 |
请完成以下Java代码 | public void setPA_SLA_Goal_ID (int PA_SLA_Goal_ID)
{
if (PA_SLA_Goal_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, Integer.valueOf(PA_SLA_Goal_ID));
}
/** Get SLA Goal.
@return Service Level Agreement Goal
*/
public int getPA_SLA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Goal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null) | {
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Goal.java | 1 |
请完成以下Java代码 | public void setJAXBObjectFactory(final DynamicObjectFactory jaxbObjectFactory)
{
this.jaxbObjectFactory = jaxbObjectFactory;
}
private Object createXMLObject(final String xml)
{
try
{
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
final Source source = createXMLSourceFromString(xml);
final JAXBElement<?> jaxbElement = (JAXBElement<?>)unmarshaller.unmarshal(source);
final Object xmlRequestObj = jaxbElement.getValue();
return xmlRequestObj;
}
catch (JAXBException e)
{
throw new AdempiereException("Cannot convert string to xml object: " + xml, e);
}
}
private String createStringFromXMLObject(final Object xmlObject)
{
try | {
final JAXBElement<Object> jaxbElement = jaxbObjectFactory.createJAXBElement(xmlObject);
final Marshaller marshaller = jaxbContext.createMarshaller();
final StringWriter writer = new StringWriter();
marshaller.marshal(jaxbElement, writer);
final String xmlObjectStr = writer.toString();
return xmlObjectStr;
}
catch (JAXBException e)
{
throw new AdempiereException("Cannot convert xml object to string: " + xmlObject, e);
}
}
private Source createXMLSourceFromString(final String xmlStr)
{
final InputStream inputStream = new ByteArrayInputStream(xmlStr == null ? new byte[0] : xmlStr.getBytes(StandardCharsets.UTF_8));
return new StreamSource(inputStream);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\api\impl\MockedImportHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
JsonArgumentResolver jsonArgumentResolver = new JsonArgumentResolver();
argumentResolvers.add(jsonArgumentResolver);
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(2);
return bean;
}
/** Static resource locations */
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { | registry.addResourceHandler("/resources/**")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
@Bean
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
beanNameViewResolver.setOrder(1);
return beanNameViewResolver;
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-5\src\main\java\com\baeldung\spring\web\config\WebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private I_C_Project_Repair_Consumption_Summary retrieveRecordByGroupingKey(@NonNull final ServiceRepairProjectConsumptionSummary.GroupingKey groupingKey)
{
return queryBL.createQueryBuilder(I_C_Project_Repair_Consumption_Summary.class)
.addEqualsFilter(I_C_Project_Repair_Consumption_Summary.COLUMNNAME_C_Project_ID, groupingKey.getProjectId())
.addEqualsFilter(I_C_Project_Repair_Consumption_Summary.COLUMNNAME_M_Product_ID, groupingKey.getProductId())
.addEqualsFilter(I_C_Project_Repair_Consumption_Summary.COLUMNNAME_C_UOM_ID, groupingKey.getUomId())
.create()
.firstOnly(I_C_Project_Repair_Consumption_Summary.class);
}
private List<I_C_Project_Repair_Consumption_Summary> retrieveRecordByProjectId(@NonNull final ProjectId projectId)
{
return queryBL.createQueryBuilder(I_C_Project_Repair_Consumption_Summary.class)
.addEqualsFilter(I_C_Project_Repair_Consumption_Summary.COLUMNNAME_C_Project_ID, projectId)
.create()
.listImmutable(I_C_Project_Repair_Consumption_Summary.class);
}
public void saveProject(
@NonNull final ProjectId projectId,
@NonNull final Collection<ServiceRepairProjectConsumptionSummary> newValues)
{
if (newValues.stream().anyMatch(newValue -> !ProjectId.equals(newValue.getGroupingKey().getProjectId(), projectId)))
{
throw new AdempiereException("all values shall match " + projectId + ": " + newValues); | }
final HashMap<ServiceRepairProjectConsumptionSummary.GroupingKey, I_C_Project_Repair_Consumption_Summary> existingRecordsByGroupingKey = new HashMap<>(Maps.uniqueIndex(
retrieveRecordByProjectId(projectId),
ServiceRepairProjectConsumptionSummaryRepository::extractGroupingKey));
for (final ServiceRepairProjectConsumptionSummary newValue : newValues)
{
final I_C_Project_Repair_Consumption_Summary existingRecord = existingRecordsByGroupingKey.remove(newValue.getGroupingKey());
final I_C_Project_Repair_Consumption_Summary record = existingRecord != null
? existingRecord
: InterfaceWrapperHelper.newInstance(I_C_Project_Repair_Consumption_Summary.class);
updateRecord(record, newValue);
InterfaceWrapperHelper.saveRecord(record);
}
InterfaceWrapperHelper.deleteAll(existingRecordsByGroupingKey.values());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\repository\ServiceRepairProjectConsumptionSummaryRepository.java | 2 |
请完成以下Java代码 | public void setRevision(int revision) {
this.revision = revision;
}
@Override
public int getRevision() {
return revision;
}
@Override
public int getRevisionNext() {
return revision + 1;
}
public String getHistoryConfiguration() {
return historyConfiguration;
}
public void setHistoryConfiguration(String historyConfiguration) {
this.historyConfiguration = historyConfiguration;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", incidentTimestamp=" + incidentTimestamp
+ ", incidentType=" + incidentType
+ ", executionId=" + executionId
+ ", activityId=" + activityId
+ ", processInstanceId=" + processInstanceId
+ ", processDefinitionId=" + processDefinitionId
+ ", causeIncidentId=" + causeIncidentId
+ ", rootCauseIncidentId=" + rootCauseIncidentId
+ ", configuration=" + configuration
+ ", tenantId=" + tenantId
+ ", incidentMessage=" + incidentMessage
+ ", jobDefinitionId=" + jobDefinitionId
+ ", failedActivityId=" + failedActivityId
+ ", annotation=" + annotation
+ "]";
} | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IncidentEntity other = (IncidentEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IncidentEntity.java | 1 |
请完成以下Java代码 | public BalanceType12Code getCd() {
return cd;
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link BalanceType12Code }
*
*/
public void setCd(BalanceType12Code value) {
this.cd = value;
}
/**
* Gets the value of the prtry property.
*
* @return
* possible object is
* {@link String }
* | */
public String getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrtry(String value) {
this.prtry = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BalanceType5Choice.java | 1 |
请完成以下Java代码 | public void onSuccess(TbQueueMsgMetadata metadata) {
stats.incrementSuccessful();
}
@Override
public void onFailure(Throwable t) {
log.error("[{}] Failed to send response {}", requestId, response, t);
sendErrorResponse(requestId, tpi, request, t);
stats.incrementFailed();
}
});
},
e -> {
pendingRequestCount.decrementAndGet();
if (e.getCause() != null && e.getCause() instanceof TimeoutException) {
log.warn("[{}] Timeout to process the request: {}", requestId, request, e);
} else {
log.trace("[{}] Failed to process the request: {}", requestId, request, e);
}
stats.incrementFailed();
},
requestTimeout,
scheduler,
callbackExecutor);
} catch (Throwable e) {
pendingRequestCount.decrementAndGet();
log.warn("[{}] Failed to process the request: {}", requestId, request, e);
stats.incrementFailed();
}
}
});
consumer.commit();
}
private void sendErrorResponse(UUID requestId, TopicPartitionInfo tpi, Request request, Throwable cause) {
Response errorResponseMsg = handler.constructErrorResponseMsg(request, cause);
if (errorResponseMsg != null) {
errorResponseMsg.getHeaders().put(REQUEST_ID_HEADER, uuidToBytes(requestId));
responseProducer.send(tpi, errorResponseMsg, null); | }
}
public void subscribe(Set<TopicPartitionInfo> partitions) {
requestConsumer.update(partitions);
}
public void stop() {
if (requestConsumer != null) {
requestConsumer.stop();
requestConsumer.awaitStop();
}
if (responseProducer != null) {
responseProducer.stop();
}
if (scheduler != null) {
scheduler.shutdownNow();
}
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\PartitionedQueueResponseTemplate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
bookstoreService.persistTwoBooks();
System.out.println("\n\n===========================================");
System.out.println("First call fetchBook() ................"); | bookstoreService.fetchBook();
System.out.println("Second call fetchBook() ................");
bookstoreService.fetchBook();
System.out.println("\n\n===========================================");
System.out.println("First call fetchBookByPrice() ................");
bookstoreService.fetchBookByPrice();
System.out.println("Second call fetchBookByPrice() ................");
bookstoreService.fetchBookByPrice();
};
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootHibernateSLCEhCacheKickoff\src\main\java\com\bookstore\MainApplication.java | 2 |
请完成以下Java代码 | public class JtaRetryInterceptor extends RetryInterceptor {
private final Logger log = LoggerFactory.getLogger(JtaRetryInterceptor.class);
protected final TransactionManager transactionManager;
public JtaRetryInterceptor(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
public <T> T execute(CommandConfig config, Command<T> command) {
if (calledInsideTransaction()) {
log.trace("Called inside transaction, skipping the retry interceptor.");
return next.execute(config, command);
} else { | return super.execute(config, command);
}
}
protected boolean calledInsideTransaction() {
try {
return transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION;
} catch (SystemException e) {
throw new ActivitiException(
"Could not determine the current status of the transaction manager: " + e.getMessage(),
e
);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\JtaRetryInterceptor.java | 1 |
请完成以下Java代码 | public void update(User dbUser) {
dbUser.setId(getId());
dbUser.setFirstName(getFirstName());
dbUser.setLastName(getLastName());
dbUser.setEmail(getEmail());
}
// getter / setters ////////////////////////////////////
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
} | public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserProfileDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
ps.setLong(1, 1L);
ps.setString(2, image.getName());
lobCreator.setBlobAsBinaryStream(ps, 3, imageInStream, (int) image.length());
}
}
);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public List<Map<String, InputStream>> findImageByBookId(Long bookId) {
List<Map<String, InputStream>> result = jdbcTemplate.query(
"select id, book_id, filename, blob_image from book_image where book_id = ?",
new Object[]{bookId},
new RowMapper<Map<String, InputStream>>() {
public Map<String, InputStream> mapRow(ResultSet rs, int i) throws SQLException {
String fileName = rs.getString("filename");
InputStream blob_image_stream = lobHandler.getBlobAsBinaryStream(rs, "blob_image"); | // byte array
//Map<String, Object> results = new HashMap<>();
//byte[] blobBytes = lobHandler.getBlobAsBytes(rs, "blob_image");
//results.put("BLOB", blobBytes);
Map<String, InputStream> results = new HashMap<>();
results.put(fileName, blob_image_stream);
return results;
}
});
return result;
}
} | repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\repository\JdbcBookRepository.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOutputName() {
return outputName;
}
public void setOutputName(String outputName) {
this.outputName = outputName;
}
public DmnTypeDefinition getTypeDefinition() { | return typeDefinition;
}
public void setTypeDefinition(DmnTypeDefinition typeDefinition) {
this.typeDefinition = typeDefinition;
}
@Override
public String toString() {
return "DmnDecisionTableOutputImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", outputName='" + outputName + '\'' +
", typeDefinition=" + typeDefinition +
'}';
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionTableOutputImpl.java | 1 |
请完成以下Java代码 | private static void hppcMap() {
//Regular maps
IntLongHashMap intLongHashMap = new IntLongHashMap();
intLongHashMap.put(25,1L);
intLongHashMap.put(150,Long.MAX_VALUE);
intLongHashMap.put(1,0L);
intLongHashMap.get(150);
IntObjectMap<BigDecimal> intObjectMap = new IntObjectHashMap<BigDecimal>();
intObjectMap.put(1, BigDecimal.valueOf(1));
intObjectMap.put(2, BigDecimal.valueOf(2500));
BigDecimal value = intObjectMap.get(2);
//Scatter maps
IntLongScatterMap intLongScatterMap = new IntLongScatterMap();
intLongScatterMap.put(1, 1L);
intLongScatterMap.put(2, -2L);
intLongScatterMap.put(1000,0L);
intLongScatterMap.get(1000);
IntObjectScatterMap<BigDecimal> intObjectScatterMap = new IntObjectScatterMap<BigDecimal>();
intObjectScatterMap.put(1, BigDecimal.valueOf(1));
intObjectScatterMap.put(2, BigDecimal.valueOf(2500));
value = intObjectScatterMap.get(2);
}
private static void fastutilMap() {
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap();
int2BooleanMap.put(1, true);
int2BooleanMap.put(7, false);
int2BooleanMap.put(4, true);
boolean value = int2BooleanMap.get(1);
//Lambda style iteration | Int2BooleanMaps.fastForEach(int2BooleanMap, entry -> {
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
});
//Iterator based loop
ObjectIterator<Int2BooleanMap.Entry> iterator = Int2BooleanMaps.fastIterator(int2BooleanMap);
while(iterator.hasNext()) {
Int2BooleanMap.Entry entry = iterator.next();
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
}
}
private static void eclipseCollectionsMap() {
MutableIntIntMap mutableIntIntMap = IntIntMaps.mutable.empty();
mutableIntIntMap.addToValue(1, 1);
ImmutableIntIntMap immutableIntIntMap = IntIntMaps.immutable.empty();
MutableObjectDoubleMap<String> dObject = ObjectDoubleMaps.mutable.empty();
dObject.addToValue("price", 150.5);
dObject.addToValue("quality", 4.4);
dObject.addToValue("stability", 0.8);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\primitives\PrimitiveMaps.java | 1 |
请完成以下Java代码 | private boolean hasBoundValueObject(String beanName) {
return BindMethod.VALUE_OBJECT.equals(BindMethodAttribute.get(this.registry, beanName));
}
private void bind(@Nullable ConfigurationPropertiesBean bean) {
if (bean == null) {
return;
}
Assert.state(bean.asBindTarget().getBindMethod() != BindMethod.VALUE_OBJECT,
"Cannot bind @ConfigurationProperties for bean '" + bean.getName()
+ "'. Ensure that @ConstructorBinding has not been applied to regular bean");
try {
this.binder.bind(bean);
}
catch (Exception ex) {
throw new ConfigurationPropertiesBindException(bean, ex);
}
}
/**
* Register a {@link ConfigurationPropertiesBindingPostProcessor} bean if one is not | * already registered.
* @param registry the bean definition registry
* @since 2.2.0
*/
public static void register(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "'registry' must not be null");
if (!registry.containsBeanDefinition(BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder
.rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class)
.getBeanDefinition();
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(BEAN_NAME, definition);
}
ConfigurationPropertiesBinder.register(registry);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesBindingPostProcessor.java | 1 |
请完成以下Java代码 | public void validate() {
index();
}
public void updateCompatibilityRange(VersionParser versionParser) {
this.indexedDependencies.values().forEach((it) -> it.updateCompatibilityRange(versionParser));
}
@Override
public void merge(List<DependencyGroup> otherContent) {
otherContent.forEach((group) -> {
if (this.content.stream()
.noneMatch((it) -> group.getName() != null && group.getName().equals(it.getName()))) {
this.content.add(group);
}
});
index();
}
private void index() {
this.indexedDependencies.clear();
this.content.forEach((group) -> group.content.forEach((dependency) -> {
// Apply defaults
if (dependency.getCompatibilityRange() == null && group.getCompatibilityRange() != null) {
dependency.setCompatibilityRange(group.getCompatibilityRange());
}
if (dependency.getBom() == null && group.getBom() != null) {
dependency.setBom(group.getBom());
}
if (dependency.getRepository() == null && group.getRepository() != null) { | dependency.setRepository(group.getRepository());
}
dependency.resolve();
indexDependency(dependency.getId(), dependency);
for (String alias : dependency.getAliases()) {
indexDependency(alias, dependency);
}
}));
}
private void indexDependency(String id, Dependency dependency) {
Dependency existing = this.indexedDependencies.get(id);
if (existing != null) {
throw new IllegalArgumentException("Could not register " + dependency + " another dependency "
+ "has also the '" + id + "' id " + existing);
}
this.indexedDependencies.put(id, dependency);
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\DependenciesCapability.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void reopenPickingJob()
{
if (!jobToReopen.getDocStatus().isCompleted())
{
return;
}
final PickingJob reopenedJob = jobToReopen
.withDocStatus(PickingJobDocStatus.Drafted)
.withLockedBy(null);
pickingJobRepository.save(reservePickingSlotIfPossible(reopenedJob));
jobToReopen.getLines().forEach(this::reactivateLine);
}
@NonNull
private PickingJob reservePickingSlotIfPossible(@NonNull final PickingJob pickingJob)
{
final PickingSlotId slotId = pickingJob.getPickingSlotId()
.orElse(null);
if (slotId == null)
{
return pickingJob;
}
return PickingJobAllocatePickingSlotCommand.builder()
.pickingJobRepository(pickingJobRepository)
.pickingSlotService(pickingSlotService)
.pickingJob(pickingJob.withPickingSlot(null))
.pickingSlotId(slotId)
.failIfNotAllocated(false)
.build()
.execute();
}
private void reactivateLine(@NonNull final PickingJobLine line)
{ | line.getSteps().forEach(this::reactivateStepIfNeeded);
}
private void reactivateStepIfNeeded(@NonNull final PickingJobStep step)
{
final IMutableHUContext huContext = huService.createMutableHUContextForProcessing();
step.getPickFroms().getKeys()
.stream()
.map(key -> step.getPickFroms().getPickFrom(key))
.map(PickingJobStepPickFrom::getPickedTo)
.filter(Objects::nonNull)
.map(PickingJobStepPickedTo::getActualPickedHUs)
.flatMap(List::stream)
.filter(pickStepHu -> huIdsToPick.containsKey(pickStepHu.getActualPickedHU().getId()))
.forEach(pickStepHU -> {
final HuId huId = pickStepHU.getActualPickedHU().getId();
final I_M_HU hu = huService.getById(huId);
shipmentScheduleService.addQtyPickedAndUpdateHU(AddQtyPickedRequest.builder()
.scheduleId(step.getScheduleId())
.qtyPicked(CatchWeightHelper.extractQtys(
huContext,
step.getProductId(),
pickStepHU.getQtyPicked(),
hu))
.tuOrVHU(hu)
.huContext(huContext)
.anonymousHuPickedOnTheFly(huIdsToPick.get(huId).isAnonymousHuPickedOnTheFly())
.build());
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobReopenCommand.java | 2 |
请完成以下Java代码 | public class Todo {
int userId;
int id;
String title;
boolean completed;
public Todo() {
}
public Todo(int userId, int id, String title, boolean completed) {
this.userId = userId;
this.id = id;
this.title = title;
this.completed = completed;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed; | }
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Todo todo = (Todo) o;
return userId == todo.userId && id == todo.id && completed == todo.completed && Objects.equals(title, todo.title);
}
@Override
public int hashCode() {
return Objects.hash(userId, id, title, completed);
}
@Override
public String toString() {
return "{" + "userId=" + userId + ", id=" + id + ", title='" + title + '\'' + ", completed=" + completed + '}';
}
} | repos\tutorials-master\core-java-modules\core-java-11-3\src\main\java\com\baeldung\httppojo\Todo.java | 1 |
请完成以下Java代码 | public String getCaption(final String adLanguage)
{
return getPreconditionsResolution().computeCaption(processCaption, adLanguage);
}
public String getDescription(final String adLanguage)
{
return processDescription.translate(adLanguage);
}
public int getSortNo()
{
return getPreconditionsResolution().getSortNo().orElse(this.sortNo);
}
private ProcessPreconditionsResolution getPreconditionsResolution()
{
return preconditionsResolutionSupplier.get().getValue();
}
public Duration getPreconditionsResolutionCalcDuration()
{
return preconditionsResolutionSupplier.get().getDuration();
}
public boolean isDisabled()
{
return getPreconditionsResolution().isRejected();
}
public boolean isEnabled()
{
final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution();
return preconditionsResolution.isAccepted();
}
public boolean isEnabledOrNotSilent()
{
try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(I_AD_Process.Table_Name, processId == null ? null : processId.toAdProcessIdOrNull()))
{
final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution();
return preconditionsResolution.isAccepted() || !preconditionsResolution.isInternal();
}
}
public boolean isInternal()
{
final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution();
return preconditionsResolution.isInternal();
}
public String getDisabledReason(final String adLanguage)
{
return getPreconditionsResolution().getRejectReason().translate(adLanguage);
}
public Map<String, Object> getDebugProperties()
{
final ImmutableMap.Builder<String, Object> debugProperties = ImmutableMap.builder(); | if (debugProcessClassname != null)
{
debugProperties.put("debug-classname", debugProcessClassname);
}
return debugProperties.build();
}
public boolean isDisplayedOn(@NonNull final DisplayPlace displayPlace)
{
return getDisplayPlaces().contains(displayPlace);
}
@Value
private static class ValueAndDuration<T>
{
public static <T> ValueAndDuration<T> fromSupplier(final Supplier<T> supplier)
{
final Stopwatch stopwatch = Stopwatch.createStarted();
final T value = supplier.get();
final Duration duration = Duration.ofNanos(stopwatch.stop().elapsed(TimeUnit.NANOSECONDS));
return new ValueAndDuration<>(value, duration);
}
T value;
Duration duration;
private ValueAndDuration(final T value, final Duration duration)
{
this.value = value;
this.duration = duration;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\WebuiRelatedProcessDescriptor.java | 1 |
请完成以下Java代码 | public class RocketChatNotifier extends AbstractContentNotifier {
private static final String DEFAULT_MESSAGE = "*#{name}* (#{id}) is *#{status}*";
private RestTemplate restTemplate;
/**
* Host URL for RocketChat server
*/
@Nullable
private String url;
/**
* Room Id to send message
*/
@Nullable
private String roomId;
/**
* Token for RocketChat API
*/
@Nullable
private String token;
/**
* User Id for RocketChat API
*/
private String userId;
public RocketChatNotifier(InstanceRepository repository, RestTemplate restTemplate) {
super(repository);
this.restTemplate = restTemplate;
}
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("X-Auth-Token", token);
headers.add("X-User-Id", userId);
return Mono.fromRunnable(() -> restTemplate.exchange(getUri(), HttpMethod.POST,
new HttpEntity<>(createMessage(event, instance), headers), Void.class));
}
private URI getUri() {
if (url == null) {
throw new IllegalStateException("'url' must not be null.");
}
return URI.create(String.format("%s/api/v1/chat.sendMessage", url));
}
protected Object createMessage(InstanceEvent event, Instance instance) {
Map<String, String> messageJsonData = new HashMap<>();
messageJsonData.put("rid", roomId);
messageJsonData.put("msg", createContent(event, instance));
Map<String, Object> messageJson = new HashMap<>();
messageJson.put("message", messageJsonData);
return messageJson;
}
@Override
protected Map<String, Object> buildContentModel(InstanceEvent event, Instance instance) {
var content = super.buildContentModel(event, instance);
content.put("roomId", roomId);
return content;
}
@Override
protected String getDefaultMessage() {
return DEFAULT_MESSAGE;
} | public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Nullable
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Nullable
public String getRoomId() {
return roomId;
}
public void setRoomId(String roomId) {
this.roomId = roomId;
}
@Nullable
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
@Nullable
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\RocketChatNotifier.java | 1 |
请完成以下Java代码 | public ServerResponse handle(ServerRequest serverRequest) {
URI uri = uriResolver.apply(serverRequest);
MultiValueMap<String, String> params = MvcUtils.encodeQueryParams(serverRequest.params());
// @formatter:off
URI url = UriComponentsBuilder.fromUri(serverRequest.uri())
.scheme(uri.getScheme())
.host(uri.getHost())
.port(uri.getPort())
.replaceQueryParams(params)
.build(true)
.toUri();
// @formatter:on
HttpHeaders filteredRequestHeaders = filterHeaders(this.requestHttpHeadersFilters,
serverRequest.headers().asHttpHeaders(), serverRequest);
boolean preserveHost = (boolean) serverRequest.attributes()
.getOrDefault(MvcUtils.PRESERVE_HOST_HEADER_ATTRIBUTE, false);
if (preserveHost) {
filteredRequestHeaders.set(HttpHeaders.HOST, serverRequest.headers().firstHeader(HttpHeaders.HOST));
}
else {
filteredRequestHeaders.remove(HttpHeaders.HOST);
}
// @formatter:off
ProxyExchange.Request proxyRequest = proxyExchange.request(serverRequest).uri(url)
.headers(filteredRequestHeaders)
// TODO: allow injection of ResponseConsumer
.responseConsumer((response, serverResponse) -> {
HttpHeaders httpHeaders = filterHeaders(this.responseHttpHeadersFilters, response.getHeaders(), serverResponse); | serverResponse.headers().putAll(httpHeaders);
})
.build();
// @formatter:on
return proxyExchange.exchange(proxyRequest);
}
private <REQUEST_OR_RESPONSE> HttpHeaders filterHeaders(@Nullable List<?> filters, HttpHeaders original,
REQUEST_OR_RESPONSE requestOrResponse) {
HttpHeaders filtered = original;
if (CollectionUtils.isEmpty(filters)) {
return filtered;
}
for (Object filter : filters) {
@SuppressWarnings("unchecked")
HttpHeadersFilter<REQUEST_OR_RESPONSE> typed = ((HttpHeadersFilter<REQUEST_OR_RESPONSE>) filter);
filtered = typed.apply(filtered, requestOrResponse);
}
return filtered;
}
public interface URIResolver extends Function<ServerRequest, URI> {
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\ProxyExchangeHandlerFunction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public User getById(int id) {
logger.info("获取用户start...");
// 从缓存中获取用户信息
String key = "user_" + id;
ValueOperations<String, User> operations = redisTemplate.opsForValue();
// 缓存存在
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
User user = operations.get(key);
logger.info("从缓存中获取了用户 id = " + id);
return user;
}
// 缓存不存在,从 DB 中获取
User user = userMapper.selectById(id);
// 插入缓存
operations.set(key, user, 10, TimeUnit.SECONDS);
return user;
}
/**
* 更新用户
* 如果缓存存在,删除
* 如果缓存不存在,不操作
*
* @param user 用户
*/
public void updateUser(User user) {
logger.info("更新用户start...");
userMapper.updateById(user);
int userId = user.getId();
// 缓存存在,删除缓存
String key = "user_" + userId;
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) { | redisTemplate.delete(key);
logger.info("更新用户时候,从缓存中删除用户 >> " + userId);
}
}
/**
* 删除用户
* 如果缓存中存在,删除
*/
public void deleteById(int id) {
logger.info("删除用户start...");
userMapper.deleteById(id);
// 缓存存在,删除缓存
String key = "user_" + id;
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
logger.info("更新用户时候,从缓存中删除用户 >> " + id);
}
}
} | repos\SpringBootBucket-master\springboot-redis\src\main\java\com\xncoding\pos\service\UserService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void reportActivity(TransportProtos.SessionInfoProto sessionInfo) {
transportService.recordActivity(sessionInfo);
}
@Override
public String getName() {
return DataConstants.SNMP_TRANSPORT_NAME;
}
@PreDestroy
public void shutdown() {
log.info("Stopping SNMP transport!");
if (scheduler != null) {
scheduler.shutdownNow();
}
if (executor != null) {
executor.shutdownNow();
}
if (snmp != null) {
try {
snmp.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
log.info("SNMP transport stopped!");
}
@Data
private static class RequestContext {
private final Integer requestId;
private final SnmpCommunicationSpec communicationSpec;
private final SnmpMethod method;
private final List<SnmpMapping> responseMappings;
private final int requestSize;
private List<PDU> responseParts; | @Builder
public RequestContext(Integer requestId, SnmpCommunicationSpec communicationSpec, SnmpMethod method, List<SnmpMapping> responseMappings, int requestSize) {
this.requestId = requestId;
this.communicationSpec = communicationSpec;
this.method = method;
this.responseMappings = responseMappings;
this.requestSize = requestSize;
if (requestSize > 1) {
this.responseParts = Collections.synchronizedList(new ArrayList<>());
}
}
}
private interface ResponseDataMapper {
JsonObject map(List<PDU> pdus, RequestContext requestContext);
}
private interface ResponseProcessor {
void process(JsonObject responseData, RequestContext requestContext, DeviceSessionContext sessionContext);
}
} | repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\service\SnmpTransportService.java | 2 |
请完成以下Java代码 | public class MigrationPlanGenerationDto {
protected String sourceProcessDefinitionId;
protected String targetProcessDefinitionId;
protected boolean updateEventTriggers;
protected Map<String, VariableValueDto> variables;
public String getSourceProcessDefinitionId() {
return sourceProcessDefinitionId;
}
public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) {
this.sourceProcessDefinitionId = sourceProcessDefinitionId;
}
public String getTargetProcessDefinitionId() {
return targetProcessDefinitionId;
}
public void setTargetProcessDefinitionId(String targetProcessDefinitionId) {
this.targetProcessDefinitionId = targetProcessDefinitionId; | }
public boolean isUpdateEventTriggers() {
return updateEventTriggers;
}
public void setUpdateEventTriggers(boolean updateEventTriggers) {
this.updateEventTriggers = updateEventTriggers;
}
public void setVariables(Map<String, VariableValueDto> variables) {
this.variables = variables;
}
public Map<String, VariableValueDto> getVariables() {
return variables;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigrationPlanGenerationDto.java | 1 |
请完成以下Java代码 | public class HalUser extends HalResource<HalUser> implements HalIdResource {
public final static HalRelation REL_SELF =
HalRelation.build("self", UserRestService.class, UriBuilder.fromPath(UserRestService.PATH).path("{id}"));
protected String id;
protected String firstName;
protected String lastName;
protected String email;
public static HalUser fromUser(User user) {
HalUser halUser = new HalUser();
halUser.id = user.getId();
halUser.firstName = user.getFirstName();
halUser.lastName = user.getLastName();
halUser.email = user.getEmail();
halUser.linker.createLink(REL_SELF, user.getId());
return halUser;
} | public String getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\user\HalUser.java | 1 |
请完成以下Java代码 | public Stream<IHUProductStorage> streamHUProductStorages(@NonNull final List<I_M_HU> hus)
{
return hus.stream()
.map(this::getStorage)
.flatMap(IHUStorage::streamProductStorages);
}
@Override
public boolean isSingleProductWithQtyEqualsTo(@NonNull final I_M_HU hu, @NonNull final ProductId productId, @NonNull final Quantity qty)
{
return getStorage(hu).isSingleProductWithQtyEqualsTo(productId, qty);
}
@Override
public boolean isSingleProductStorageMatching(@NonNull final I_M_HU hu, @NonNull final ProductId productId)
{
return getStorage(hu).isSingleProductStorageMatching(productId);
}
@NonNull
public IHUProductStorage getSingleHUProductStorage(@NonNull final I_M_HU hu)
{
return getStorage(hu).getSingleHUProductStorage();
}
@Override
public List<IHUProductStorage> getProductStorages(@NonNull final I_M_HU hu)
{ | return getStorage(hu).getProductStorages();
}
@Override
public IHUProductStorage getProductStorage(@NonNull final I_M_HU hu, @NonNull ProductId productId)
{
return getStorage(hu).getProductStorage(productId);
}
@Override
public @NonNull ImmutableMap<HuId, Set<ProductId>> getHUProductIds(@NonNull final List<I_M_HU> hus)
{
final Map<HuId, Set<ProductId>> huId2ProductIds = new HashMap<>();
streamHUProductStorages(hus)
.forEach(productStorage -> {
final Set<ProductId> productIds = new HashSet<>();
productIds.add(productStorage.getProductId());
huId2ProductIds.merge(productStorage.getHuId(), productIds, (oldValues, newValues) -> {
oldValues.addAll(newValues);
return oldValues;
});
});
return ImmutableMap.copyOf(huId2ProductIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\DefaultHUStorageFactory.java | 1 |
请完成以下Java代码 | private void createDetailLines()
{
StringBuffer sb = new StringBuffer ("INSERT INTO T_ReportStatement "
+ "(AD_PInstance_ID, Fact_Acct_ID, LevelNo,"
+ "DateAcct, Name, Description,"
+ "AmtAcctDr, AmtAcctCr, Balance, Qty) ");
sb.append("SELECT ").append(getPinstanceId().getRepoId()).append(",Fact_Acct_ID,1,")
.append("TRUNC(DateAcct),NULL,NULL,"
+ "AmtAcctDr, AmtAcctCr, AmtAcctDr-AmtAcctCr, Qty "
+ "FROM Fact_Acct "
+ "WHERE ").append(m_parameterWhere)
.append(" AND TRUNC(DateAcct) BETWEEN ").append(DB.TO_DATE(p_DateAcct_From))
.append(" AND ").append(DB.TO_DATE(p_DateAcct_To));
//
int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName());
log.debug("#" + no);
log.trace(sb.toString());
// Set Name,Description
String sql_select = "SELECT e.Name, fa.Description " | + "FROM Fact_Acct fa"
+ " INNER JOIN AD_Table t ON (fa.AD_Table_ID=t.AD_Table_ID)"
+ " INNER JOIN AD_Element e ON (t.TableName||'_ID'=e.ColumnName) "
+ "WHERE r.Fact_Acct_ID=fa.Fact_Acct_ID";
// Translated Version ...
sb = new StringBuffer ("UPDATE T_ReportStatement r SET (Name,Description)=(")
.append(sql_select).append(") "
+ "WHERE Fact_Acct_ID <> 0 AND AD_PInstance_ID=").append(getPinstanceId().getRepoId());
//
no = DB.executeUpdateAndSaveErrorOnFail(DB.convertSqlToNative(sb.toString()), get_TrxName());
log.debug("Name #" + no);
log.trace("Name - " + sb);
} // createDetailLines
} // FinStatement | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\report\FinStatement.java | 1 |
请完成以下Java代码 | public long getBestellPzn() {
return bestellPzn;
}
/**
* Sets the value of the bestellPzn property.
*
*/
public void setBestellPzn(long value) {
this.bestellPzn = value;
}
/**
* Gets the value of the bestellMenge property.
*
*/
public int getBestellMenge() {
return bestellMenge;
}
/**
* Sets the value of the bestellMenge property.
*
*/
public void setBestellMenge(int value) {
this.bestellMenge = value;
}
/**
* Gets the value of the bestellLiefervorgabe property.
*
* @return
* possible object is
* {@link Liefervorgabe }
*
*/
public Liefervorgabe getBestellLiefervorgabe() {
return bestellLiefervorgabe;
}
/**
* Sets the value of the bestellLiefervorgabe property.
*
* @param value
* allowed object is
* {@link Liefervorgabe }
*
*/
public void setBestellLiefervorgabe(Liefervorgabe value) {
this.bestellLiefervorgabe = value;
}
/**
* Gets the value of the substitution property.
*
* @return
* possible object is
* {@link BestellungSubstitution }
*
*/
public BestellungSubstitution getSubstitution() {
return substitution;
} | /**
* Sets the value of the substitution property.
*
* @param value
* allowed object is
* {@link BestellungSubstitution }
*
*/
public void setSubstitution(BestellungSubstitution value) {
this.substitution = value;
}
/**
* Gets the value of the anteile property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the anteile property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAnteile().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link BestellungAnteil }
*
*
*/
public List<BestellungAnteil> getAnteile() {
if (anteile == null) {
anteile = new ArrayList<BestellungAnteil>();
}
return this.anteile;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungAntwortPosition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private MSV3ServerConfig retrieveServerConfig()
{
final MSV3ServerConfigBuilder serverConfigBuilder = MSV3ServerConfig.builder();
final I_MSV3_Server serverConfigRecord = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_MSV3_Server.class)
.addOnlyActiveRecordsFilter()
.create()
.firstOnly(I_MSV3_Server.class);
if (serverConfigRecord != null)
{
final int fixedQtyAvailableToPromise = serverConfigRecord.getFixedQtyAvailableToPromise();
serverConfigBuilder.fixedQtyAvailableToPromise(fixedQtyAvailableToPromise);
final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class);
final WarehousePickingGroupId warehousePickingGroupId = WarehousePickingGroupId.ofRepoId(serverConfigRecord.getM_Warehouse_PickingGroup_ID()); | // note that the DAO method invoked by this supplier is cached
serverConfigBuilder.warehousePickingGroupSupplier(() -> warehouseDAO.getWarehousePickingGroupById(warehousePickingGroupId));
}
Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_MSV3_Server_Product_Category.class)
.addOnlyActiveRecordsFilter()
.create()
.list(I_MSV3_Server_Product_Category.class)
.forEach(productCategoryRecord -> serverConfigBuilder.productCategoryId(ProductCategoryId.ofRepoId(productCategoryRecord.getM_Product_Category_ID())));
return serverConfigBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\services\MSV3ServerConfigRepository.java | 2 |
请完成以下Java代码 | protected EventDefinitionParse createEventParseFromResource(EventResourceEntity resource) {
String resourceName = resource.getName();
ByteArrayInputStream inputStream = new ByteArrayInputStream(resource.getBytes());
EventDefinitionParse eventParse = eventDefinitionParseFactory.createParse()
.sourceInputStream(inputStream)
.setSourceSystemId(resourceName)
.deployment(deployment)
.name(resourceName);
eventParse.execute(CommandContextUtil.getEventRegistryConfiguration());
return eventParse;
}
protected ChannelDefinitionParse createChannelParseFromResource(EventResourceEntity resource) {
String resourceName = resource.getName();
ByteArrayInputStream inputStream = new ByteArrayInputStream(resource.getBytes());
ChannelDefinitionParse eventParse = channelDefinitionParseFactory.createParse()
.sourceInputStream(inputStream)
.setSourceSystemId(resourceName)
.deployment(deployment)
.name(resourceName);
eventParse.execute(CommandContextUtil.getEventRegistryConfiguration());
return eventParse;
}
protected boolean isEventResource(String resourceName) {
for (String suffix : EVENT_RESOURCE_SUFFIXES) {
if (resourceName.endsWith(suffix)) {
return true;
}
} | return false;
}
protected boolean isChannelResource(String resourceName) {
for (String suffix : CHANNEL_RESOURCE_SUFFIXES) {
if (resourceName.endsWith(suffix)) {
return true;
}
}
return false;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\ParsedDeploymentBuilder.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("\n\nFetch Author as Streamable:");
bookstoreService.fetchAuthorsAsStreamable();
System.out.println("\n\nFetch Author DTO as Streamable:");
bookstoreService.fetchAuthorsDtoAsStreamable();
System.out.println("\n\nFetch Author by genre and age as Streamable:");
bookstoreService.fetchAuthorsByGenreAndAgeGreaterThan();
System.out.println("\n\nFetch Author by genre or age as Streamable:");
bookstoreService.fetchAuthorsByGenreOrAgeGreaterThan(); | System.out.println("\n\nDON'T DO THIS! Fetch all columns just to drop a part of them:");
bookstoreService.fetchAuthorsNames1();
System.out.println("\n\nDO THIS! Fetch only the needed columns:");
bookstoreService.fetchAuthorsNames2();
System.out.println("\n\nDON'T DO THIS! Fetch more rows than needed just to throw away a part of it:");
bookstoreService.fetchAuthorsOlderThanAge1();
System.out.println("\n\nDO THIS! Fetch only the needed rows:");
bookstoreService.fetchAuthorsOlderThanAge2();
System.out.println("\n\nCAUTION! Concatenating two Streamable:");
bookstoreService.fetchAuthorsByGenreConcatAge();
};
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootStreamable\src\main\java\com\bookstore\MainApplication.java | 1 |
请完成以下Java代码 | class SysConfigMap
{
private final ImmutableMap<String, SysConfigEntry> entries;
public SysConfigMap(@NonNull final ImmutableMap<String, SysConfigEntry> entries)
{
this.entries = entries;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("size", entries.size())
.toString();
} | public ImmutableList<String> getNamesForPrefix(@NonNull final String prefix, @NonNull final ClientAndOrgId clientAndOrgId)
{
return entries.values()
.stream()
.filter(entry -> entry.isNameStartsWith(prefix))
.filter(entry -> entry.isClientAndOrgMatching(clientAndOrgId))
.map(SysConfigEntry::getName)
.collect(ImmutableList.toImmutableList());
}
public Optional<String> getValueAsString(@NonNull final String name, @NonNull final ClientAndOrgId clientAndOrgId)
{
final SysConfigEntry entry = entries.get(name);
return entry != null ? entry.getValueAsString(clientAndOrgId) : Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigMap.java | 1 |
请完成以下Java代码 | public static LocalDateTime roundToStartOfMonthUsingLocalDateTime(LocalDateTime dateTime) {
return dateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
}
public static LocalDateTime roundToEndOfWeekUsingLocalDateTime(LocalDateTime dateTime) {
return dateTime.with(TemporalAdjusters.next(DayOfWeek.SATURDAY))
.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999);
}
public static ZonedDateTime roundToStartOfMonthUsingZonedDateTime(ZonedDateTime dateTime) {
return dateTime.withDayOfMonth(1)
.withHour(0)
.withMinute(0)
.withSecond(0)
.with(ChronoField.MILLI_OF_SECOND, 0) | .with(ChronoField.MICRO_OF_SECOND, 0)
.with(ChronoField.NANO_OF_SECOND, 0);
}
public static ZonedDateTime roundToEndOfWeekUsingZonedDateTime(ZonedDateTime dateTime) {
return dateTime.with(TemporalAdjusters.next(DayOfWeek.SATURDAY))
.withHour(23)
.withMinute(59)
.withSecond(59)
.with(ChronoField.MILLI_OF_SECOND, 999)
.with(ChronoField.MICRO_OF_SECOND, 999)
.with(ChronoField.NANO_OF_SECOND, 999);
}
} | repos\tutorials-master\core-java-modules\core-java-8-datetime-2\src\main\java\com\baeldung\rounddate\RoundDate.java | 1 |
请完成以下Java代码 | public void setT_Qty (final @Nullable BigDecimal T_Qty)
{
set_Value (COLUMNNAME_T_Qty, T_Qty);
}
@Override
public BigDecimal getT_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Time (final @Nullable java.sql.Timestamp T_Time)
{
set_Value (COLUMNNAME_T_Time, T_Time);
}
@Override
public java.sql.Timestamp getT_Time()
{ | return get_ValueAsTimestamp(COLUMNNAME_T_Time);
}
@Override
public void setTest_ID (final int Test_ID)
{
if (Test_ID < 1)
set_ValueNoCheck (COLUMNNAME_Test_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Test_ID, Test_ID);
}
@Override
public int getTest_ID()
{
return get_ValueAsInt(COLUMNNAME_Test_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Test.java | 1 |
请完成以下Java代码 | public static HUReservationDocRef ofProjectId(@NonNull final ProjectId projectId) {return HUReservationDocRef.builder().projectId(projectId).build();}
public static HUReservationDocRef ofPickingJobStepId(@NonNull final PickingJobStepId pickingJobStepId) {return HUReservationDocRef.builder().pickingJobStepId(pickingJobStepId).build();}
public static HUReservationDocRef ofDDOrderLineId(@NonNull final DDOrderLineId ddOrderLineId) {return HUReservationDocRef.builder().ddOrderLineId(ddOrderLineId).build();}
@Builder
private HUReservationDocRef(
@Nullable final OrderLineId salesOrderLineId,
@Nullable final ProjectId projectId,
@Nullable final PickingJobStepId pickingJobStepId,
@Nullable DDOrderLineId ddOrderLineId)
{
if (CoalesceUtil.countNotNulls(salesOrderLineId, projectId, pickingJobStepId, ddOrderLineId) != 1)
{
throw new AdempiereException("One and only one document shall be set")
.appendParametersToMessage()
.setParameter("salesOrderLineId", salesOrderLineId)
.setParameter("projectId", projectId)
.setParameter("pickingJobStepId", pickingJobStepId)
.setParameter("ddOrderLineId", ddOrderLineId);
}
this.salesOrderLineId = salesOrderLineId;
this.projectId = projectId;
this.pickingJobStepId = pickingJobStepId;
this.ddOrderLineId = ddOrderLineId;
}
public static boolean equals(@Nullable final HUReservationDocRef ref1, @Nullable final HUReservationDocRef ref2) {return Objects.equals(ref1, ref2);}
public interface CaseMappingFunction<R>
{
R salesOrderLineId(@NonNull OrderLineId salesOrderLineId);
R projectId(@NonNull ProjectId projectId);
R pickingJobStepId(@NonNull PickingJobStepId pickingJobStepId);
R ddOrderLineId(@NonNull DDOrderLineId ddOrderLineId);
}
public <R> R map(@NonNull final CaseMappingFunction<R> mappingFunction)
{ | if (salesOrderLineId != null)
{
return mappingFunction.salesOrderLineId(salesOrderLineId);
}
else if (projectId != null)
{
return mappingFunction.projectId(projectId);
}
else if (pickingJobStepId != null)
{
return mappingFunction.pickingJobStepId(pickingJobStepId);
}
else if (ddOrderLineId != null)
{
return mappingFunction.ddOrderLineId(ddOrderLineId);
}
else
{
throw new IllegalStateException("Unknown state: " + this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationDocRef.java | 1 |
请完成以下Java代码 | private void createAndHandleAddDetailRequest(
@NonNull final DetailDataRecordIdentifier identifier,
@NonNull final ReceiptScheduleCreatedEvent receiptScheduleCreatedEvent)
{
final OrderLineDescriptor orderLineDescriptor = //
receiptScheduleCreatedEvent.getOrderLineDescriptor();
final InsertDetailRequestBuilder addDetailsRequest = InsertDetailRequest.builder()
.detailDataRecordIdentifier(identifier);
addDetailsRequest
.qtyOrdered(receiptScheduleCreatedEvent.getMaterialDescriptor().getQuantity())
.qtyReserved(receiptScheduleCreatedEvent.getReservedQuantity())
.docTypeId(orderLineDescriptor.getDocTypeId())
.orderId(orderLineDescriptor.getOrderId())
.orderLineId(orderLineDescriptor.getOrderLineId())
.bPartnerId(orderLineDescriptor.getOrderBPartnerId());
detailRequestHandler.handleInsertDetailRequest(addDetailsRequest.build());
}
private void createAndHandleMainDataRequestForOldValues(
@NonNull final OldReceiptScheduleData oldReceiptScheduleData, | @NonNull final MainDataRecordIdentifier identifier)
{
final BigDecimal oldOrderedQuantity = oldReceiptScheduleData.getOldOrderedQuantity();
final BigDecimal oldReservedQuantity = oldReceiptScheduleData.getOldReservedQuantity();
if (oldOrderedQuantity.signum() == 0
&& oldReservedQuantity.signum() == 0)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Skipping this event because it has both oldOrderedQuantityDelta and oldReservedQuantityDelta = zero");
return;
}
final UpdateMainDataRequest request = UpdateMainDataRequest.builder()
.identifier(identifier)
.orderedPurchaseQty(oldOrderedQuantity.negate())
.qtySupplyPurchaseOrder(oldReservedQuantity.negate())
.build();
dataUpdateRequestHandler.handleDataUpdateRequest(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\eventhandler\ReceiptScheduleEventHandler.java | 1 |
请完成以下Java代码 | public WindowId getWindowId()
{
return MaterialCockpitUtil.WINDOWID_MaterialCockpitView;
}
@Override
public void put(final IView view)
{
defaultViewsRepositoryStorage.put(view);
}
@Nullable
@Override
public IView getByIdOrNull(final ViewId viewId)
{
return defaultViewsRepositoryStorage.getByIdOrNull(viewId);
}
@Override | public void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction)
{
defaultViewsRepositoryStorage.closeById(viewId, closeAction);
}
@Override
public Stream<IView> streamAllViews()
{
return defaultViewsRepositoryStorage.streamAllViews();
}
@Override
public void invalidateView(final ViewId viewId)
{
defaultViewsRepositoryStorage.invalidateView(viewId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitViewsIndexStorage.java | 1 |
请完成以下Java代码 | private static void setUserMemoFields(@NonNull final I_I_BPartner importRecord, @NonNull final I_AD_User user)
{
setUserMemo(user, importRecord.getAD_User_Memo1());
setUserMemo(user, importRecord.getAD_User_Memo2());
setUserMemo(user, importRecord.getAD_User_Memo3());
setUserMemo(user, importRecord.getAD_User_Memo4());
}
private static void setUserMemo(@NonNull final I_AD_User user, final String newMemoText)
{
if (!Check.isEmpty(newMemoText, true))
{
if (Check.isEmpty(user.getMemo(), true))
{
user.setMemo(newMemoText);
}
else | {
user.setMemo(user.getMemo()
.concat("\n")
.concat(newMemoText));
}
}
}
private static void setDefaultFlagsForContact(@NonNull final I_I_BPartner importRecord, @NonNull final I_AD_User user)
{
user.setIsDefaultContact(importRecord.isDefaultContact());
user.setIsBillToContact_Default(importRecord.isBillToContact_Default());
user.setIsShipToContact_Default(importRecord.isShipToContact_Default());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerContactImportHelper.java | 1 |
请完成以下Java代码 | public boolean supports(Class<?> authentication) {
return OidcLogoutAuthenticationToken.class.isAssignableFrom(authentication);
}
/**
* Sets the {@code Consumer} providing access to the
* {@link OidcLogoutAuthenticationContext} and is responsible for validating specific
* OpenID Connect RP-Initiated Logout Request parameters associated in the
* {@link OidcLogoutAuthenticationToken}. The default authentication validator is
* {@link OidcLogoutAuthenticationValidator}.
*
* <p>
* <b>NOTE:</b> The authentication validator MUST throw
* {@link OAuth2AuthenticationException} if validation fails.
* @param authenticationValidator the {@code Consumer} providing access to the
* {@link OidcLogoutAuthenticationContext} and is responsible for validating specific
* OpenID Connect RP-Initiated Logout Request parameters
*/
public void setAuthenticationValidator(Consumer<OidcLogoutAuthenticationContext> authenticationValidator) {
Assert.notNull(authenticationValidator, "authenticationValidator cannot be null");
this.authenticationValidator = authenticationValidator;
}
private SessionInformation findSessionInformation(Authentication principal, String sessionId) {
List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(principal.getPrincipal(), true);
SessionInformation sessionInformation = null;
if (!CollectionUtils.isEmpty(sessions)) {
for (SessionInformation session : sessions) {
if (session.getSessionId().equals(sessionId)) {
sessionInformation = session;
break;
} | }
}
return sessionInformation;
}
private static void throwError(String errorCode, String parameterName) {
OAuth2Error error = new OAuth2Error(errorCode, "OpenID Connect 1.0 Logout Request Parameter: " + parameterName,
"https://openid.net/specs/openid-connect-rpinitiated-1_0.html#ValidationAndErrorHandling");
throw new OAuth2AuthenticationException(error);
}
private static String createHash(String value) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcLogoutAuthenticationProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void updateAuthor2() {
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronizationAdapter() {
@Override
public void afterCompletion(int status) {
logger.info("After completion (method) ...");
}
@Override
public void afterCommit() {
logger.info("After commit (method) ...");
}
@Override | public void beforeCompletion() {
logger.info("Before completion (method) ...");
}
@Override
public void beforeCommit(boolean readOnly) {
logger.info("Before commit (method) ...");
}
});
Author author = authorRepository.findById(1L).orElseThrow();
author.setAge(51);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionCallback\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public List<Integer> retrieveChangeLogAllowedTableIds()
{
final ImmutableList.Builder<Integer> list = ImmutableList.builder();
final String sql = "SELECT t.AD_Table_ID FROM AD_Table t "
+ "WHERE t.IsChangeLog='Y'" // also inactive
+ " OR EXISTS (SELECT * FROM AD_Column c "
+ "WHERE t.AD_Table_ID=c.AD_Table_ID AND c.ColumnName='EntityType') "
+ "ORDER BY t.AD_Table_ID";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
rs = pstmt.executeQuery();
while (rs.next())
{
list.add(rs.getInt(1)); | }
}
catch (final Exception e)
{
logger.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
return list.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\impl\SessionDAO.java | 1 |
请完成以下Java代码 | private boolean isLocalDataSet(Region<?, ?> region) {
return region instanceof LocalDataSet;
}
private boolean isNotLocalDataSet(Region<?, ?> region) {
return !isLocalDataSet(region);
}
private boolean isRegionAttributesPresent(Region<?, ?> region) {
return region != null && region.getAttributes() != null;
}
private boolean isStatisticsEnabled(Region<?, ?> region) {
return isRegionAttributesPresent(region) && region.getAttributes().getStatisticsEnabled();
}
private String cachePartitionRegionKey(String regionName, String suffix) {
return cacheRegionKey(regionName, String.format("partition.%s", suffix));
}
private String cacheRegionKey(String regionName, String suffix) {
return String.format("geode.cache.regions.%1$s.%2$s", regionName, suffix);
} | private String cacheRegionEvictionKey(String regionName, String suffix) {
return cacheRegionKey(regionName, String.format("eviction.%s", suffix));
}
private String cacheRegionExpirationKey(String regionName, String suffix) {
return cacheRegionKey(regionName, String.format("expiration.%s", suffix));
}
private String cacheRegionStatisticsKey(String regionName, String suffix) {
return cacheRegionKey(regionName, String.format("statistics.%s", suffix));
}
private String emptyIfUnset(String value) {
return StringUtils.hasText(value) ? value : "";
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\GeodeRegionsHealthIndicator.java | 1 |
请完成以下Java代码 | public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getDecisionEntityManager(commandContext).findDecisionCountByQueryCriteria(this);
}
@Override
public List<DmnDecision> executeList(CommandContext commandContext) {
return CommandContextUtil.getDecisionEntityManager(commandContext).findDecisionsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public Set<String> getDeploymentIds() {
return deploymentIds;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getDecisionId() {
return decisionId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public Integer getVersion() {
return version;
}
public Integer getVersionGt() {
return versionGt;
}
public Integer getVersionGte() {
return versionGte;
}
public Integer getVersionLt() {
return versionLt;
} | public Integer getVersionLte() {
return versionLte;
}
public boolean isLatest() {
return latest;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getDecisionType() {
return decisionType;
}
public String getDecisionTypeLike() {
return decisionTypeLike;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DecisionQueryImpl.java | 1 |
请完成以下Java代码 | public VPanelFormFieldBuilder setColumnName(String columnName)
{
this.columnName = columnName;
return this;
}
private boolean isSameLine()
{
return sameLine;
}
/**
* Default: {@link #DEFAULT_SameLine}
*
* @param sameLine If true, the new Field will be added in the same line.
*/
public VPanelFormFieldBuilder setSameLine(boolean sameLine)
{
this.sameLine = sameLine;
return this;
}
private boolean isMandatory()
{
return mandatory;
}
/**
* Default: {@link #DEFAULT_Mandatory}
*
* @param mandatory true if this field shall be marked as mandatory
*/
public VPanelFormFieldBuilder setMandatory(boolean mandatory)
{
this.mandatory = mandatory;
return this;
}
private boolean isAutocomplete()
{
if (autocomplete != null)
{
return autocomplete;
}
// if Search, always auto-complete
if (DisplayType.Search == displayType)
{
return true;
}
return false;
}
public VPanelFormFieldBuilder setAutocomplete(boolean autocomplete)
{
this.autocomplete = autocomplete;
return this;
}
private int getAD_Column_ID()
{
// not set is allowed
return AD_Column_ID;
}
/**
* @param AD_Column_ID Column for lookups. | */
public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID)
{
this.AD_Column_ID = AD_Column_ID;
return this;
}
public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName)
{
return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID());
}
private EventListener getEditorListener()
{
// null allowed
return editorListener;
}
/**
* @param listener VetoableChangeListener that gets called if the field is changed.
*/
public VPanelFormFieldBuilder setEditorListener(EventListener listener)
{
this.editorListener = listener;
return this;
}
public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel)
{
this.bindEditorToModel = bindEditorToModel;
return this;
}
public VPanelFormFieldBuilder setReadOnly(boolean readOnly)
{
this.readOnly = readOnly;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java | 1 |
请完成以下Java代码 | public class Calculator {
public static void main(String[] args) {
HTMLDocument document = HTMLDocument.current();
HTMLElement container = document.getElementById("calculator-container");
// Create input fields
HTMLInputElement input1 = (HTMLInputElement) document.createElement("input");
input1.setType("number");
container.appendChild(input1);
HTMLInputElement input2 = (HTMLInputElement) document.createElement("input");
input2.setType("number");
container.appendChild(input2);
// Create a button
HTMLButtonElement button = (HTMLButtonElement) document.createElement("button");
button.appendChild(document.createTextNode("Calculate Sum"));
container.appendChild(button);
// Create a div to display the result
HTMLElement resultDiv = document.createElement("div");
container.appendChild(resultDiv); | // Add click event listener to the button
button.addEventListener("click", (evt) -> {
try {
long num1 = Long.parseLong(input1.getValue());
long num2 = Long.parseLong(input2.getValue());
long sum = num1 + num2;
resultDiv.setTextContent("Result: " + sum);
} catch (NumberFormatException e) {
resultDiv.setTextContent("Please enter valid integer numbers.");
}
});
}
@JSExport
public static int sum(int a, int b) {
return a + b;
}
} | repos\tutorials-master\libraries-bytecode\src\main\java\com\baeldung\teavm\Calculator.java | 1 |
请完成以下Java代码 | public class TreeStore {
private final TreeCache cache;
private final TreeBuilder builder;
/**
* Constructor.
* @param builder the tree builder
* @param cache the tree cache (may be <code>null</code>)
*/
public TreeStore(TreeBuilder builder, TreeCache cache) {
super();
this.builder = builder;
this.cache = cache;
}
public TreeBuilder getBuilder() {
return builder;
} | /**
* Get a {@link Tree}.
* If a tree for the given expression is present in the cache, it is
* taken from there; otherwise, the expression string is parsed and
* the resulting tree is added to the cache.
* @param expression expression string
* @return expression tree
*/
public Tree get(String expression) throws TreeBuilderException {
if (cache == null) {
return builder.build(expression);
}
Tree tree = cache.get(expression);
if (tree == null) {
cache.put(expression, tree = builder.build(expression));
}
return tree;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\TreeStore.java | 1 |
请完成以下Java代码 | protected String encodeNonNullPassword(String rawPassword) {
byte[] salt = this.saltGenerator.generateKey();
byte[] hash = new byte[this.hashLength];
// @formatter:off
Argon2Parameters params = new Argon2Parameters
.Builder(Argon2Parameters.ARGON2_id)
.withSalt(salt)
.withParallelism(this.parallelism)
.withMemoryAsKB(this.memory)
.withIterations(this.iterations)
.build();
// @formatter:on
Argon2BytesGenerator generator = new Argon2BytesGenerator();
generator.init(params);
generator.generateBytes(rawPassword.toString().toCharArray(), hash);
return Argon2EncodingUtils.encode(hash, params);
}
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
Argon2EncodingUtils.Argon2Hash decoded;
try {
decoded = Argon2EncodingUtils.decode(encodedPassword);
}
catch (IllegalArgumentException ex) {
this.logger.warn("Malformed password hash", ex);
return false;
}
byte[] hashBytes = new byte[decoded.getHash().length];
Argon2BytesGenerator generator = new Argon2BytesGenerator();
generator.init(decoded.getParameters());
generator.generateBytes(rawPassword.toString().toCharArray(), hashBytes);
return constantTimeArrayEquals(decoded.getHash(), hashBytes);
} | @Override
protected boolean upgradeEncodingNonNull(String encodedPassword) {
Argon2Parameters parameters = Argon2EncodingUtils.decode(encodedPassword).getParameters();
return parameters.getMemory() < this.memory || parameters.getIterations() < this.iterations;
}
private static boolean constantTimeArrayEquals(byte[] expected, byte[] actual) {
if (expected.length != actual.length) {
return false;
}
int result = 0;
for (int i = 0; i < expected.length; i++) {
result |= expected[i] ^ actual[i];
}
return result == 0;
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\argon2\Argon2PasswordEncoder.java | 1 |
请完成以下Java代码 | public String getIP_Address ()
{
return (String)get_Value(COLUMNNAME_IP_Address);
}
/** Set Last Synchronized.
@param LastSynchronized
Date when last synchronized
*/
public void setLastSynchronized (Timestamp LastSynchronized)
{
set_Value (COLUMNNAME_LastSynchronized, LastSynchronized);
}
/** Get Last Synchronized.
@return Date when last synchronized
*/
public Timestamp getLastSynchronized ()
{
return (Timestamp)get_Value(COLUMNNAME_LastSynchronized);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/ | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_BroadcastServer.java | 1 |
请完成以下Java代码 | public EdgeId getId() {
return super.getId();
}
@Schema(description = "Timestamp of the edge creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public long getCreatedTime() {
return super.getCreatedTime();
}
@Schema(description = "JSON object with Tenant Id. Use 'assignDeviceToTenant' to change the Tenant Id.", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public TenantId getTenantId() {
return this.tenantId;
}
@Schema(description = "JSON object with Customer Id. Use 'assignEdgeToCustomer' to change the Customer Id.", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public CustomerId getCustomerId() {
return this.customerId;
}
@Schema(description = "JSON object with Root Rule Chain Id. Use 'setEdgeRootRuleChain' to change the Root Rule Chain Id.", accessMode = Schema.AccessMode.READ_ONLY)
public RuleChainId getRootRuleChainId() {
return this.rootRuleChainId;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Edge Name in scope of Tenant", example = "Silo_A_Edge")
@Override
public String getName() { | return this.name;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge type", example = "Silos")
public String getType() {
return this.type;
}
@Schema(description = "Label that may be used in widgets", example = "Silo Edge on far field")
public String getLabel() {
return this.label;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge routing key ('username') to authorize on cloud")
public String getRoutingKey() {
return this.routingKey;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge secret ('password') to authorize on cloud")
public String getSecret() {
return this.secret;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\edge\Edge.java | 1 |
请完成以下Java代码 | private static class PrinterQueue
{
@NonNull private final HardwarePrinter printer;
@NonNull private final ArrayList<PrintingDataAndSegment> segments = new ArrayList<>();
public void add(
@NonNull PrintingData printingData,
@NonNull PrintingSegment segment)
{
Check.assumeEquals(this.printer, segment.getPrinter(), "Expected segment printer to match: {}, expected={}", segment, printer);
segments.add(PrintingDataAndSegment.of(printingData, segment));
}
public FrontendPrinterDataItem toFrontendPrinterData()
{
return FrontendPrinterDataItem.builder()
.printer(printer)
.filename(suggestFilename())
.data(toByteArray())
.build();
}
private byte[] toByteArray()
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos))
{
for (PrintingDataAndSegment printingDataAndSegment : segments)
{
pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment());
}
}
return baos.toByteArray();
} | private String suggestFilename()
{
final ImmutableSet<String> filenames = segments.stream()
.map(PrintingDataAndSegment::getDocumentFileName)
.collect(ImmutableSet.toImmutableSet());
return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf";
}
}
@Value(staticConstructor = "of")
private static class PrintingDataAndSegment
{
@NonNull PrintingData printingData;
@NonNull PrintingSegment segment;
public String getDocumentFileName()
{
return printingData.getDocumentFileName();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<T> findAll() {
return Lists.newArrayList(getDao().findAll());
}
@Override
public Page<T> findPaginated(final int page, final int size) {
return getDao().findAll(PageRequest.of(page, size));
}
// write
@Override
public T create(final T entity) {
return getDao().save(entity);
}
@Override
public T update(final T entity) { | return getDao().save(entity);
}
@Override
public void delete(final T entity) {
getDao().delete(entity);
}
@Override
public void deleteById(final long entityId) {
getDao().deleteById(entityId);
}
protected abstract JpaRepository<T, Long> getDao();
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\persistence\service\common\AbstractService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public UnitType getOrderedQuantity() {
return orderedQuantity;
}
/**
* Sets the value of the orderedQuantity property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setOrderedQuantity(UnitType value) {
this.orderedQuantity = value;
}
/**
* Gets the value of the deliveredQuantity property.
*
* @return
* possible object is
* {@link UnitType }
*
*/
public UnitType getDeliveredQuantity() {
return deliveredQuantity;
}
/**
* Sets the value of the deliveredQuantity property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setDeliveredQuantity(UnitType value) {
this.deliveredQuantity = value;
}
/**
* Gets the value of the quantityVariances property.
*
* @return
* possible object is
* {@link UnitType }
*
*/
public UnitType getQuantityVariances() {
return quantityVariances;
}
/**
* Sets the value of the quantityVariances property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setQuantityVariances(UnitType value) {
this.quantityVariances = value;
}
/**
* Gets the value of the variancesReasonCode property.
* | * @return
* possible object is
* {@link String }
*
*/
public String getVariancesReasonCode() {
return variancesReasonCode;
}
/**
* Sets the value of the variancesReasonCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVariancesReasonCode(String value) {
this.variancesReasonCode = value;
}
/**
* Gets the value of the contractReference property.
*
* @return
* possible object is
* {@link ReferenceType }
*
*/
public ReferenceType getContractReference() {
return contractReference;
}
/**
* Sets the value of the contractReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setContractReference(ReferenceType value) {
this.contractReference = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\RECADVListLineItemExtensionType.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.