instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class SysRolePermission implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
private String id;
/**
* 角色id
*/
private String roleId;
/**
* 权限id
*/
private String permissionId;
/**
* 数据权限
*/
private String dataRuleIds;
/**
* 操作时间
*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date operateDate;
|
/**
* 操作ip
*/
private String operateIp;
public SysRolePermission() {
}
public SysRolePermission(String roleId, String permissionId) {
this.roleId = roleId;
this.permissionId = permissionId;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysRolePermission.java
| 1
|
请完成以下Java代码
|
public class AtomicOperationTransitionCreateScope implements AtomicOperation {
private static final Logger LOGGER = LoggerFactory.getLogger(AtomicOperationTransitionCreateScope.class);
@Override
public boolean isAsync(InterpretableExecution execution) {
ActivityImpl activity = (ActivityImpl) execution.getActivity();
return activity.isAsync();
}
@Override
public void execute(InterpretableExecution execution) {
InterpretableExecution propagatingExecution = null;
ActivityImpl activity = (ActivityImpl) execution.getActivity();
if (activity.isScope()) {
propagatingExecution = (InterpretableExecution) execution.createExecution();
|
propagatingExecution.setActivity(activity);
propagatingExecution.setTransition(execution.getTransition());
execution.setTransition(null);
execution.setActivity(null);
execution.setActive(false);
LOGGER.debug("create scope: parent {} continues as execution {}", execution, propagatingExecution);
propagatingExecution.initialize();
} else {
propagatingExecution = execution;
}
propagatingExecution.performOperation(AtomicOperation.TRANSITION_NOTIFY_LISTENER_START);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationTransitionCreateScope.java
| 1
|
请完成以下Java代码
|
private static IZoomSource retrieveZoomSourceOrNull(final String tableName, final MQuery query, final AdWindowId adWindowId)
{
final PO po = new Query(Env.getCtx(), tableName, query.getWhereClause(), ITrx.TRXNAME_None)
.firstOnly(PO.class);
if (po == null)
{
return null;
}
return POZoomSource.of(po, adWindowId);
}
private AZoomAcross(final JComponent invoker, IZoomSource source)
{
logger.info("source={}", source);
final String adLanguage = Env.getAD_Language(Env.getCtx());
final List<RelatedDocuments> relatedDocumentsList = retrieveZoomTargets(source);
for (final RelatedDocuments relatedDocuments : relatedDocumentsList)
{
final String caption = relatedDocuments.getCaption().translate(adLanguage);
m_popup.add(caption).addActionListener(event -> launch(relatedDocuments));
}
if (relatedDocumentsList.isEmpty())
{
m_popup.add(Services.get(IMsgBL.class).getMsg(Env.getCtx(), "NoZoomTarget")); // Added
}
if (invoker.isShowing())
{
m_popup.show(invoker, 0, invoker.getHeight());
}
}
private final JPopupMenu m_popup = new JPopupMenu("ZoomMenu");
private static final Logger logger = LogManager.getLogger(AZoomAcross.class);
private List<RelatedDocuments> retrieveZoomTargets(final IZoomSource source)
{
if (source == null)
{
return ImmutableList.of(); // guard against NPE
|
}
// in Swing this is not needed because we have the Posted button
SpringContextHolder.instance.getBean(FactAcctRelatedDocumentsProvider.class).disable();
final RelatedDocumentsFactory relatedDocumentsFactory = SpringContextHolder.instance.getBean(RelatedDocumentsFactory.class);
final RelatedDocumentsPermissions permissions = RelatedDocumentsPermissionsFactory.ofRolePermissions(Env.getUserRolePermissions());
return relatedDocumentsFactory.retrieveRelatedDocuments(source, permissions);
}
private void launch(final RelatedDocuments relatedDocuments)
{
final AdWindowId adWindowId = relatedDocuments.getAdWindowId();
final MQuery query = relatedDocuments.getQuery();
logger.info("AD_Window_ID={} - {}", adWindowId, query);
AWindow frame = new AWindow();
if (!frame.initWindow(adWindowId, query))
{
return;
}
AEnv.addToWindowManager(frame);
if (Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED))
{
AEnv.showMaximized(frame);
}
else
{
AEnv.showCenterScreen(frame);
}
frame = null;
} // launchZoom
} // AZoom
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AZoomAcross.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Object aggregationGroupAvg() {
// 使用管道操作符 $group 进行分组,然后统计各个组文档某字段值平均值
AggregationOperation group = Aggregation.group("sex").avg("salary").as("salaryAvg");
// 将操作加入到聚合对象中
Aggregation aggregation = Aggregation.newAggregation(group);
// 执行聚合查询
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
return results.getMappedResults();
}
/**
* 使用管道操作符 $group 结合表达式操作符 $first 获取每个组的包含某字段的文档的第一条数据
*
* @return 聚合结果
*/
public Object aggregationGroupFirst() {
// 先对数据进行排序,然后使用管道操作符 $group 进行分组,最后统计各个组文档某字段值第一个值
AggregationOperation sort = Aggregation.sort(Sort.by("salary").ascending());
AggregationOperation group = Aggregation.group("sex").first("salary").as("salaryFirst");
// 将操作加入到聚合对象中
Aggregation aggregation = Aggregation.newAggregation(sort, group);
// 执行聚合查询
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
return results.getMappedResults();
}
/**
* 使用管道操作符 $group 结合表达式操作符 $last 获取每个组的包含某字段的文档的最后一条数据
*
* @return 聚合结果
*/
public Object aggregationGroupLast() {
// 先对数据进行排序,然后使用管道操作符 $group 进行分组,最后统计各个组文档某字段值第最后一个值
|
AggregationOperation sort = Aggregation.sort(Sort.by("salary").ascending());
AggregationOperation group = Aggregation.group("sex").last("salary").as("salaryLast");
// 将操作加入到聚合对象中
Aggregation aggregation = Aggregation.newAggregation(sort, group);
// 执行聚合查询
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
return results.getMappedResults();
}
/**
* 使用管道操作符 $group 结合表达式操作符 $push 获取某字段列表
*
* @return 聚合结果
*/
public Object aggregationGroupPush() {
// 先对数据进行排序,然后使用管道操作符 $group 进行分组,然后以数组形式列出某字段的全部值
AggregationOperation push = Aggregation.group("sex").push("salary").as("salaryFirst");
// 将操作加入到聚合对象中
Aggregation aggregation = Aggregation.newAggregation(push);
// 执行聚合查询
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
return results.getMappedResults();
}
}
|
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\AggregateGroupService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> getRedisInfo() throws Exception {
List<RedisInfo> infoList = this.redisService.getRedisInfo();
//log.info(infoList.toString());
return Result.ok(infoList);
}
/**
* Redis历史性能指标查询(过去一小时)
* @return
* @throws Exception
* @author chenrui
* @date 2024/5/14 14:56
*/
@GetMapping(value = "/metrics/history")
public Result<?> getMetricsHistory() throws Exception {
Map<String,List<Map<String,Object>>> metricsHistory = this.redisService.getMetricsHistory();
return Result.OK(metricsHistory);
}
@GetMapping("/keysSize")
public Map<String, Object> getKeysSize() throws Exception {
return redisService.getKeysSize();
}
/**
* 获取redis key数量 for 报表
* @return
* @throws Exception
*/
@GetMapping("/keysSizeForReport")
public Map<String, JSONArray> getKeysSizeReport() throws Exception {
return redisService.getMapForReport("1");
}
/**
* 获取redis 内存 for 报表
*
* @return
* @throws Exception
*/
@GetMapping("/memoryForReport")
public Map<String, JSONArray> memoryForReport() throws Exception {
return redisService.getMapForReport("2");
}
/**
* 获取redis 全部信息 for 报表
* @return
* @throws Exception
|
*/
@GetMapping("/infoForReport")
public Map<String, JSONArray> infoForReport() throws Exception {
return redisService.getMapForReport("3");
}
@GetMapping("/memoryInfo")
public Map<String, Object> getMemoryInfo() throws Exception {
return redisService.getMemoryInfo();
}
/**
* @功能:获取磁盘信息
* @param request
* @param response
* @return
*/
@GetMapping("/queryDiskInfo")
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){
Result<List<Map<String,Object>>> res = new Result<>();
try {
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
log.info("查询磁盘信息:"+fs.length+"个");
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getTotalSpace()==0) {
continue;
}
Map<String,Object> map = new HashMap(5);
map.put("name", fsv.getSystemDisplayName(fs[i]));
map.put("max", fs[i].getTotalSpace());
map.put("rest", fs[i].getFreeSpace());
map.put("restPPT", (fs[i].getTotalSpace()-fs[i].getFreeSpace())*100/fs[i].getTotalSpace());
list.add(map);
log.info(map.toString());
}
res.setResult(list);
res.success("查询成功");
} catch (Exception e) {
res.error500("查询失败"+e.getMessage());
}
return res;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\controller\ActuatorRedisController.java
| 2
|
请完成以下Java代码
|
public void updateFAOpenItemTrxInfo()
{
if (openItemTrxInfo != null)
{
return;
}
this.openItemTrxInfo = services.computeOpenItemTrxInfo(this).orElse(null);
}
void setOpenItemTrxInfo(@Nullable final FAOpenItemTrxInfo openItemTrxInfo)
{
this.openItemTrxInfo = openItemTrxInfo;
}
public void updateFrom(@NonNull FactAcctChanges changes)
{
setAmtSource(changes.getAmtSourceDr(), changes.getAmtSourceCr());
|
setAmtAcct(changes.getAmtAcctDr(), changes.getAmtAcctCr());
updateCurrencyRate();
if (changes.getAccountId() != null)
{
this.accountId = changes.getAccountId();
}
setTaxIdAndUpdateVatCode(changes.getTaxId());
setDescription(changes.getDescription());
this.M_Product_ID = changes.getProductId();
this.userElementString1 = changes.getUserElementString1();
this.C_OrderSO_ID = changes.getSalesOrderId();
this.C_Activity_ID = changes.getActivityId();
this.appliedUserChanges = changes;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLine.java
| 1
|
请完成以下Java代码
|
public EventDeploymentEntity getDeployment() {
return deploymentEntity;
}
public List<EventDefinitionEntity> getAllEventDefinitions() {
return eventDefinitions;
}
public List<ChannelDefinitionEntity> getAllChannelDefinitions() {
return channelDefinitions;
}
public EventResourceEntity getResourceForEventDefinition(EventDefinitionEntity eventDefinition) {
return mapEventDefinitionsToResources.get(eventDefinition);
}
public EventDefinitionParse getEventDefinitionParseForEventDefinition(EventDefinitionEntity formDefinition) {
return mapEventDefinitionsToParses.get(formDefinition);
}
public EventModel getEventModelForEventDefinition(EventDefinitionEntity eventDefinition) {
EventDefinitionParse parse = getEventDefinitionParseForEventDefinition(eventDefinition);
return (parse == null ? null : parse.getEventModel());
}
|
public EventResourceEntity getResourceForChannelDefinition(ChannelDefinitionEntity channelDefinition) {
return mapChannelDefinitionsToResources.get(channelDefinition);
}
public ChannelDefinitionParse getChannelDefinitionParseForChannelDefinition(ChannelDefinitionEntity channelDefinition) {
return mapChannelDefinitionsToParses.get(channelDefinition);
}
public ChannelModel getChannelModelForChannelDefinition(ChannelDefinitionEntity channelDefinition) {
ChannelDefinitionParse parse = getChannelDefinitionParseForChannelDefinition(channelDefinition);
return (parse == null ? null : parse.getChannelModel());
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\ParsedDeployment.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addQtyPickedAndUpdateHU(final AddQtyPickedRequest request)
{
huShipmentScheduleBL.addQtyPickedAndUpdateHU(request);
}
public void deleteByTopLevelHUsAndShipmentScheduleId(@NonNull final Collection<I_M_HU> topLevelHUs, @NonNull final ShipmentScheduleId shipmentScheduleId)
{
huShipmentScheduleBL.deleteByTopLevelHUsAndShipmentScheduleId(topLevelHUs, shipmentScheduleId);
}
public Stream<Packageable> stream(@NonNull final PackageableQuery query)
{
return packagingDAO.stream(query);
}
public Quantity getQtyRemainingToScheduleForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord)
|
{
return huShipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentScheduleRecord);
}
public void flagForRecompute(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds)
{
huShipmentScheduleBL.flagForRecompute(shipmentScheduleIds);
}
public ShipmentScheduleLoadingCache<de.metas.handlingunits.model.I_M_ShipmentSchedule> newHuShipmentLoadingCache()
{
return huShipmentScheduleBL.newLoadingCache();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\shipmentschedule\PickingJobShipmentScheduleService.java
| 2
|
请完成以下Java代码
|
public void setC_DocBaseType_Counter_ID (int C_DocBaseType_Counter_ID)
{
if (C_DocBaseType_Counter_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DocBaseType_Counter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocBaseType_Counter_ID, Integer.valueOf(C_DocBaseType_Counter_ID));
}
/** Get C_DocBaseType_Counter.
@return C_DocBaseType_Counter */
@Override
public int getC_DocBaseType_Counter_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocBaseType_Counter_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Counter_DocBaseType.
@param Counter_DocBaseType Counter_DocBaseType */
@Override
public void setCounter_DocBaseType (java.lang.String Counter_DocBaseType)
{
set_Value (COLUMNNAME_Counter_DocBaseType, Counter_DocBaseType);
}
/** Get Counter_DocBaseType.
@return Counter_DocBaseType */
@Override
|
public java.lang.String getCounter_DocBaseType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Counter_DocBaseType);
}
/** Set Document BaseType.
@param DocBaseType
Logical type of document
*/
@Override
public void setDocBaseType (java.lang.String DocBaseType)
{
set_Value (COLUMNNAME_DocBaseType, DocBaseType);
}
/** Get Document BaseType.
@return Logical type of document
*/
@Override
public java.lang.String getDocBaseType ()
{
return (java.lang.String)get_Value(COLUMNNAME_DocBaseType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocBaseType_Counter.java
| 1
|
请完成以下Java代码
|
private int getInsertBatchSize()
{
return sysConfigBL.getIntValue(SYSCONFIG_InsertBatchSize, -1);
}
private PInstanceId getOrCreateRecordsToImportSelectionId()
{
if (_recordsToImportSelectionId == null)
{
final ImportTableDescriptor importTableDescriptor = importFormat.getImportTableDescriptor();
final DataImportRunId dataImportRunId = getOrCreateDataImportRunId();
final IQuery<Object> query = queryBL.createQueryBuilder(importTableDescriptor.getTableName())
.addEqualsFilter(ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID, dataImportRunId)
.addEqualsFilter(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg, null)
.create();
_recordsToImportSelectionId = query.createSelection();
if (_recordsToImportSelectionId == null)
{
throw new AdempiereException("No records to import for " + query);
}
}
return _recordsToImportSelectionId;
}
|
private DataImportResult createResult()
{
final Duration duration = Duration.between(startTime, SystemTime.asInstant());
return DataImportResult.builder()
.dataImportConfigId(dataImportConfigId)
.duration(duration)
//
.insertIntoImportTable(insertIntoImportTableResult)
.importRecordsValidation(validationResult)
.actualImport(actualImportResult)
.asyncImportResult(asyncImportResult)
//
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\DataImportCommand.java
| 1
|
请完成以下Java代码
|
public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO)
{
this.huAttributesDAO = huAttributesDAO;
//
// Update factory if is instantiated
if (factory != null)
{
factory.setHUAttributesDAO(huAttributesDAO);
}
}
@Override
public IHUStorageDAO getHUStorageDAO()
{
return getHUStorageFactory().getHUStorageDAO();
}
@Override
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory)
{
this.huStorageFactory = huStorageFactory;
//
// Update factory if is instantiated
if (factory != null)
{
|
factory.setHUStorageFactory(huStorageFactory);
}
}
@Override
public IHUStorageFactory getHUStorageFactory()
{
return huStorageFactory;
}
@Override
public void flush()
{
final IHUAttributesDAO huAttributesDAO = this.huAttributesDAO;
if (huAttributesDAO != null)
{
huAttributesDAO.flush();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\ClassAttributeStorageFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PaymentReservation
{
ClientId clientId;
OrgId orgId;
Money amount;
LocalDate dateTrx;
PaymentRule paymentRule;
BPartnerContactId payerContactId;
EMailAddress payerEmail;
@NonNull
@NonFinal
PaymentReservationStatus status;
OrderId salesOrderId;
@Nullable
@NonFinal
@Setter(AccessLevel.PACKAGE)
PaymentReservationId id;
@Builder
private PaymentReservation(
@NonNull final ClientId clientId,
@NonNull final OrgId orgId,
@NonNull final Money amount,
@NonNull final BPartnerContactId payerContactId,
@NonNull final EMailAddress payerEmail,
@NonNull final OrderId salesOrderId,
@NonNull final LocalDate dateTrx,
@NonNull final PaymentRule paymentRule,
@NonNull final PaymentReservationStatus status,
@Nullable final PaymentReservationId id)
|
{
this.clientId = clientId;
this.orgId = orgId;
this.amount = amount;
this.payerContactId = payerContactId;
this.payerEmail = payerEmail;
this.salesOrderId = salesOrderId;
this.dateTrx = dateTrx;
this.paymentRule = paymentRule;
this.status = status;
this.id = id;
}
public void changeStatusTo(@NonNull final PaymentReservationStatus status)
{
this.status = status;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservation.java
| 2
|
请完成以下Java代码
|
public Result train(String trainingFile, String modelFile) throws IOException
{
return train(trainingFile, trainingFile, modelFile);
}
public Result train(String trainingFile, String developFile, String modelFile) throws IOException
{
return train(trainingFile, developFile, modelFile, 0.1, 50, Runtime.getRuntime().availableProcessors());
}
private static void loadWordFromFile(String path, FrequencyMap storage, boolean segmented) throws IOException
{
BufferedReader br = IOUtility.newBufferedReader(path);
String line;
while ((line = br.readLine()) != null)
{
if (segmented)
{
for (String word : IOUtility.readLineToArray(line))
{
|
storage.add(word);
}
}
else
{
line = line.trim();
if (line.length() != 0)
{
storage.add(line);
}
}
}
br.close();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronTrainer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AwsConfigurationProperties {
@NotBlank(message = "AWS region must be configured")
private String region;
@NotBlank(message = "AWS access key must be configured")
private String accessKey;
@NotBlank(message = "AWS secret key must be configured")
private String secretKey;
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getAccessKey() {
|
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
}
|
repos\tutorials-master\aws-modules\amazon-textract\src\main\java\com\baeldung\textract\configuration\AwsConfigurationProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void initPay(@ModelAttribute ProgramPayRequestBo programPayRequestBo, BindingResult bindingResult, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
String payResultJson = "";
try{
RpUserPayConfig rpUserPayConfig = cnpPayService.checkParamAndGetUserPayConfig(programPayRequestBo, bindingResult, httpServletRequest);
//发起支付
ProgramPayResultVo resultVo = tradePaymentManagerService.programPay( rpUserPayConfig, programPayRequestBo);
payResultJson = JSONObject.toJSONString(resultVo);
logger.debug("小程序--支付结果==>{}", payResultJson);
} catch (
BizException e) {
logger.error("业务异常:", e);
payResultJson = e.getMsg();
} catch (Exception e) {
logger.error("系统异常:", e);
payResultJson = "系统异常";
}
httpServletResponse.setContentType(CONTENT_TYPE);
write(httpServletResponse, payResultJson);
|
}
@RequestMapping("/authorize")
@ResponseBody
public String wxAuthorize(@RequestParam("code") String code) {
String authUrl = WeixinConfigUtil.xAuthUrl.replace("{APPID}", WeixinConfigUtil.xAppId).replace("{SECRET}", WeixinConfigUtil.xPartnerKey).replace("{JSCODE}", code).replace("{GRANTTYPE}", WeixinConfigUtil.xGrantType);
try {
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(authUrl);
httpClient.executeMethod(getMethod);
String result = getMethod.getResponseBodyAsString();
logger.info("小程序code换取结果:{}", result);
return result;
} catch (IOException e) {
logger.info("获取openId失败!");
return null;
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\controller\ProgramPayController.java
| 2
|
请完成以下Java代码
|
protected DirContext getDirContextInstance(final @SuppressWarnings("rawtypes") Hashtable environment)
throws NamingException {
environment.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
Subject serviceSubject = login();
final NamingException[] suppressedException = new NamingException[] { null };
DirContext dirContext = Subject.doAs(serviceSubject, new PrivilegedAction<>() {
@Override
public DirContext run() {
try {
return KerberosLdapContextSource.super.getDirContextInstance(environment);
}
catch (NamingException ex) {
suppressedException[0] = ex;
return null;
}
}
});
if (suppressedException[0] != null) {
throw suppressedException[0];
}
return dirContext;
}
/**
* The login configuration to get the serviceSubject from LoginContext
* @param loginConfig the login config
*/
public void setLoginConfig(Configuration loginConfig) {
this.loginConfig = loginConfig;
}
|
private Subject login() throws AuthenticationException {
try {
LoginContext lc = new LoginContext(KerberosLdapContextSource.class.getSimpleName(), null, null,
this.loginConfig);
lc.login();
return lc.getSubject();
}
catch (LoginException ex) {
AuthenticationException ae = new AuthenticationException(ex.getMessage());
ae.initCause(ex);
throw ae;
}
}
}
|
repos\spring-security-main\kerberos\kerberos-client\src\main\java\org\springframework\security\kerberos\client\ldap\KerberosLdapContextSource.java
| 1
|
请完成以下Java代码
|
public void execute(PvmExecutionImpl execution) {
// reset activity instance id before creating the scope
execution.setActivityInstanceId(execution.getParentActivityInstanceId());
PvmExecutionImpl propagatingExecution = null;
PvmActivity activity = execution.getActivity();
if (activity.isScope()) {
propagatingExecution = execution.createExecution();
propagatingExecution.setActivity(activity);
propagatingExecution.setTransition(execution.getTransition());
execution.setTransition(null);
execution.setActive(false);
execution.setActivity(null);
LOG.createScope(execution, propagatingExecution);
|
propagatingExecution.initialize();
} else {
propagatingExecution = execution;
}
scopeCreated(propagatingExecution);
}
/**
* Called with the propagating execution
*/
protected abstract void scopeCreated(PvmExecutionImpl execution);
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationCreateScope.java
| 1
|
请完成以下Java代码
|
public ProcessEngineException resolveDelegateExpressionException(Expression expression, Class<?> parentClass, Class<JavaDelegate> javaDelegateClass) {
return new ProcessEngineException(exceptionMessage(
"033",
"Delegate Expression '{}' did neither resolve to an implementation of '{}' nor '{}'.",
expression,
parentClass,
javaDelegateClass
));
}
public ProcessEngineException shellExecutionException(Throwable cause) {
return new ProcessEngineException(exceptionMessage("034", "Could not execute shell command."), cause);
}
public void errorPropagationException(String activityId, Throwable cause) {
logError("035", "Caught an exception while propagate error in activity with id '{}'", activityId, cause);
}
public void debugConcurrentScopeIsPruned(PvmExecutionImpl execution) {
logDebug(
"036", "Concurrent scope is pruned {}", execution);
}
public void debugCancelConcurrentScopeExecution(PvmExecutionImpl execution) {
logDebug(
"037", "Cancel concurrent scope execution {}", execution);
}
public void destroyConcurrentScopeExecution(PvmExecutionImpl execution) {
logDebug(
"038", "Destroy concurrent scope execution", execution);
}
public void completeNonScopeEventSubprocess() {
logDebug(
"039", "Destroy non-socpe event subprocess");
}
public void endConcurrentExecutionInEventSubprocess() {
logDebug(
"040", "End concurrent execution in event subprocess");
}
public ProcessEngineException missingDelegateVariableMappingParentClassException(String className, String delegateVarMapping) {
|
return new ProcessEngineException(
exceptionMessage("041", "Class '{}' doesn't implement '{}'.", className, delegateVarMapping));
}
public ProcessEngineException missingBoundaryCatchEventError(String executionId, String errorCode, String errorMessage) {
return new ProcessEngineException(
exceptionMessage(
"042",
"Execution with id '{}' throws an error event with errorCode '{}' and errorMessage '{}', but no error handler was defined. ",
executionId,
errorCode,
errorMessage));
}
public ProcessEngineException missingBoundaryCatchEventEscalation(String executionId, String escalationCode) {
return new ProcessEngineException(
exceptionMessage(
"043",
"Execution with id '{}' throws an escalation event with escalationCode '{}', but no escalation handler was defined. ",
executionId,
escalationCode));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\BpmnBehaviorLogger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/user/**")
.allowedMethods("GET", "POST")
.allowedOrigins("https://javastack.cn")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(true).maxAge(3600);
}
@Bean
public ServletRegistrationBean registerServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new RegisterServlet(), "/registerServlet");
servletRegistrationBean.addInitParameter("name", "registerServlet");
servletRegistrationBean.addInitParameter("sex", "man");
servletRegistrationBean.setIgnoreRegistrationFailure(true);
return servletRegistrationBean;
}
@Bean
public ServletContextInitializer servletContextInitializer() {
return (servletContext) -> {
ServletRegistration initServlet = servletContext.addServlet("initServlet", InitServlet.class);
initServlet.addMapping("/initServlet");
initServlet.setInitParameter("name", "initServlet");
initServlet.setInitParameter("sex", "man");
};
}
@Bean
|
public RestTemplate defaultRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(Duration.ofSeconds(5))
.setReadTimeout(Duration.ofSeconds(5))
.basicAuthentication("test", "test")
.build();
}
@Bean
public RestClient defaultRestClient(RestClient.Builder restClientBuilder) {
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS
.withConnectTimeout(Duration.ofSeconds(3))
.withReadTimeout(Duration.ofSeconds(3));
ClientHttpRequestFactory requestFactory = ClientHttpRequestFactories.get(settings);
return restClientBuilder
.baseUrl("http://localhost:8080")
.defaultHeader("Authorization", "Bearer test")
.requestFactory(requestFactory)
.build();
}
}
|
repos\spring-boot-best-practice-master\spring-boot-web\src\main\java\cn\javastack\springboot\web\config\WebConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class M_HU_Reservation
{
@ModelChange( //
timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = I_M_HU_Reservation.COLUMNNAME_C_OrderLineSO_ID)
public void updateC_BPartner_ID(@NonNull final I_M_HU_Reservation huReservationRecord)
{
final I_C_OrderLine orderLineRecord = huReservationRecord.getC_OrderLineSO();
if (orderLineRecord != null)
{
huReservationRecord.setC_BPartner_Customer_ID(orderLineRecord.getC_BPartner_ID());
}
}
@ModelChange( //
timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, //
ifColumnsChanged = I_M_HU_Reservation.COLUMNNAME_IsActive)
public void setVhuReservedFlag(
@NonNull final I_M_HU_Reservation huReservationRecord,
@NonNull final ModelChangeType type)
{
final boolean reservationIsHere = type.isNew() || ModelChangeUtil.isJustActivated(huReservationRecord);
if (reservationIsHere)
{
final boolean isReserved = true;
updateVhuIsReservedFlag(huReservationRecord, isReserved);
}
}
@ModelChange( //
|
timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_BEFORE_DELETE }, //
ifColumnsChanged = I_M_HU_Reservation.COLUMNNAME_IsActive)
public void unsetVhuReservedFlag(
@NonNull final I_M_HU_Reservation huReservationRecord,
@NonNull final ModelChangeType type)
{
final boolean reservationIsGone = type.isDelete() || ModelChangeUtil.isJustDeactivated(huReservationRecord);
if (reservationIsGone)
{
final boolean isReserved = false;
updateVhuIsReservedFlag(huReservationRecord, isReserved);
}
}
private void updateVhuIsReservedFlag(
@NonNull final I_M_HU_Reservation huReservationRecord,
final boolean isReserved)
{
final HuId vhuId = HuId.ofRepoId(huReservationRecord.getVHU_ID());
Services.get(IHandlingUnitsDAO.class).setReservedByHUIds(ImmutableSet.of(vhuId), isReserved);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\interceptor\M_HU_Reservation.java
| 2
|
请完成以下Java代码
|
public class PosTagCompiler
{
/**
* 编译,比如将词性为数词的转为##数##
* @param tag 标签
* @param name 原词
* @return 编译后的等效词
*/
public static String compile(String tag, String name)
{
if (tag.startsWith("m")) return Predefine.TAG_NUMBER;
else if (tag.startsWith("nr")) return Predefine.TAG_PEOPLE;
else if (tag.startsWith("ns")) return Predefine.TAG_PLACE;
else if (tag.startsWith("nt")) return Predefine.TAG_GROUP;
else if (tag.startsWith("t")) return Predefine.TAG_TIME;
else if (tag.equals("x")) return Predefine.TAG_CLUSTER;
else if (tag.equals("nx")) return Predefine.TAG_PROPER;
else if (tag.equals("xx")) return Predefine.TAG_OTHER;
// switch (tag)
// {
// case "m":
// case "mq":
// return Predefine.TAG_NUMBER;
|
// case "nr":
// case "nr1":
// case "nr2":
// case "nrf":
// case "nrj":
// return Predefine.TAG_PEOPLE;
// case "ns":
// case "nsf":
// return Predefine.TAG_PLACE;
// case "nt":
// return Predefine.TAG_TIME;
// case "x":
// return Predefine.TAG_CLUSTER;
// case "nx":
// return Predefine.TAG_PROPER;
// }
return name;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\CoNll\PosTagCompiler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JavaPersonBean {
public String jj;
private String firstName;
private String lastName;
private String age;
private String eyesColor;
private String hairColor;
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 getAge() {
|
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getEyesColor() {
return eyesColor;
}
public void setEyesColor(String eyesColor) {
this.eyesColor = eyesColor;
}
public String getHairColor() {
return hairColor;
}
public void setHairColor(String hairColor) {
this.hairColor = hairColor;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-groovy\src\main\java\com\baeldung\groovyconfig\JavaPersonBean.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public LocalStorageDto findById(Long id){
LocalStorage localStorage = localStorageRepository.findById(id).orElseGet(LocalStorage::new);
ValidationUtil.isNull(localStorage.getId(),"LocalStorage","id",id);
return localStorageMapper.toDto(localStorage);
}
@Override
@Transactional(rollbackFor = Exception.class)
public LocalStorage create(String name, MultipartFile multipartFile) {
FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
String type = FileUtil.getFileType(suffix);
File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator);
if(ObjectUtil.isNull(file)){
throw new BadRequestException("上传失败");
}
try {
name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
LocalStorage localStorage = new LocalStorage(
file.getName(),
name,
suffix,
file.getPath(),
type,
FileUtil.getSize(multipartFile.getSize())
);
return localStorageRepository.save(localStorage);
}catch (Exception e){
FileUtil.del(file);
throw e;
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(LocalStorage resources) {
LocalStorage localStorage = localStorageRepository.findById(resources.getId()).orElseGet(LocalStorage::new);
ValidationUtil.isNull( localStorage.getId(),"LocalStorage","id",resources.getId());
localStorage.copy(resources);
localStorageRepository.save(localStorage);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteAll(Long[] ids) {
for (Long id : ids) {
LocalStorage storage = localStorageRepository.findById(id).orElseGet(LocalStorage::new);
|
FileUtil.del(storage.getPath());
localStorageRepository.delete(storage);
}
}
@Override
public void download(List<LocalStorageDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (LocalStorageDto localStorageDTO : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("文件名", localStorageDTO.getRealName());
map.put("备注名", localStorageDTO.getName());
map.put("文件类型", localStorageDTO.getType());
map.put("文件大小", localStorageDTO.getSize());
map.put("创建者", localStorageDTO.getCreateBy());
map.put("创建日期", localStorageDTO.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}
|
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\service\impl\LocalStorageServiceImpl.java
| 2
|
请完成以下Java代码
|
public class PaymentAllocationLineId implements RepoIdAware
{
@Getter private final PaymentAllocationId headerId;
private final int lineRecordId;
public PaymentAllocationLineId(@NonNull final PaymentAllocationId headerId, final int C_AllocationLine_ID)
{
this.headerId = headerId;
this.lineRecordId = Check.assumeGreaterThanZero(C_AllocationLine_ID, "C_AllocationLine_ID > 0");
}
@JsonCreator
public static PaymentAllocationLineId ofRepoId(final int C_AllocationHdr_ID, final int C_AllocationLine_ID)
{
return new PaymentAllocationLineId(PaymentAllocationId.ofRepoId(C_AllocationHdr_ID), C_AllocationLine_ID);
}
public static PaymentAllocationLineId ofRepoIdOrNull(final int C_AllocationHdr_ID, final int C_AllocationLine_ID)
{
if (C_AllocationLine_ID <= 0)
|
{
return null;
}
return new PaymentAllocationLineId(PaymentAllocationId.ofRepoId(C_AllocationHdr_ID), C_AllocationLine_ID);
}
@JsonValue
@Override
public int getRepoId() {return lineRecordId;}
public static int toRepoId(final PaymentAllocationLineId id)
{
return id != null ? id.getRepoId() : -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\PaymentAllocationLineId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setLINENUMBER(String value) {
this.linenumber = value;
}
/**
* Gets the value of the amountqual property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAMOUNTQUAL() {
return amountqual;
}
/**
* Sets the value of the amountqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAMOUNTQUAL(String value) {
this.amountqual = value;
}
/**
* Gets the value of the amount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAMOUNT() {
return amount;
}
/**
* Sets the value of the amount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAMOUNT(String value) {
this.amount = value;
|
}
/**
* Gets the value of the currency property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCY() {
return currency;
}
/**
* Sets the value of the currency property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCY(String value) {
this.currency = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DAMOU1.java
| 2
|
请完成以下Java代码
|
public void sendMail(Session session) throws MessagingException, IOException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mail@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("mail@gmail.com"));
message.setSubject("Testing Subject");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(getFile("attachment.txt"));
multipart.addBodyPart(attachmentPart);
MimeBodyPart attachmentPart2 = new MimeBodyPart();
attachmentPart2.attachFile(getFile("attachment2.txt"));
multipart.addBodyPart(attachmentPart2);
|
message.setContent(multipart);
Transport.send(message);
}
private File getFile(String filename) {
try {
URI uri = this.getClass()
.getClassLoader()
.getResource(filename)
.toURI();
return new File(uri);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to find file from resources: " + filename);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking-2\src\main\java\com\baeldung\mail\mailwithattachment\MailWithAttachmentService.java
| 1
|
请完成以下Java代码
|
public void setSerializerList(List<TypedValueSerializer<?>> serializerList) {
this.serializerList.clear();
this.serializerList.addAll(serializerList);
this.serializerMap.clear();
for (TypedValueSerializer<?> serializer : serializerList) {
serializerMap.put(serializer.getName(), serializer);
}
}
public int getSerializerIndex(TypedValueSerializer<?> serializer) {
return serializerList.indexOf(serializer);
}
public int getSerializerIndexByName(String serializerName) {
TypedValueSerializer<?> serializer = serializerMap.get(serializerName);
if(serializer != null) {
return getSerializerIndex(serializer);
} else {
return -1;
}
}
public VariableSerializers removeSerializer(TypedValueSerializer<?> serializer) {
serializerList.remove(serializer);
serializerMap.remove(serializer.getName());
return this;
}
public VariableSerializers join(VariableSerializers other) {
DefaultVariableSerializers copy = new DefaultVariableSerializers();
// "other" serializers override existing ones if their names match
for (TypedValueSerializer<?> thisSerializer : serializerList) {
TypedValueSerializer<?> serializer = other.getSerializerByName(thisSerializer.getName());
|
if (serializer == null) {
serializer = thisSerializer;
}
copy.addSerializer(serializer);
}
// add all "other" serializers that did not exist before to the end of the list
for (TypedValueSerializer<?> otherSerializer : other.getSerializers()) {
if (!copy.serializerMap.containsKey(otherSerializer.getName())) {
copy.addSerializer(otherSerializer);
}
}
return copy;
}
public List<TypedValueSerializer<?>> getSerializers() {
return new ArrayList<TypedValueSerializer<?>>(serializerList);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\DefaultVariableSerializers.java
| 1
|
请完成以下Java代码
|
public LicenseKeyDataDto getLicenseKey() {
return licenseKey;
}
public void setLicenseKey(LicenseKeyDataDto licenseKey) {
this.licenseKey = licenseKey;
}
public Set<String> getWebapps() {
return webapps;
}
public void setWebapps(Set<String> webapps) {
this.webapps = webapps;
}
public Date getDataCollectionStartDate() {
return dataCollectionStartDate;
}
public void setDataCollectionStartDate(Date dataCollectionStartDate) {
this.dataCollectionStartDate = dataCollectionStartDate;
}
public static InternalsDto fromEngineDto(Internals other) {
LicenseKeyData licenseKey = other.getLicenseKey();
|
InternalsDto dto = new InternalsDto(
DatabaseDto.fromEngineDto(other.getDatabase()),
ApplicationServerDto.fromEngineDto(other.getApplicationServer()),
licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null,
JdkDto.fromEngineDto(other.getJdk()));
dto.dataCollectionStartDate = other.getDataCollectionStartDate();
dto.commands = new HashMap<>();
other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount())));
dto.metrics = new HashMap<>();
other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount())));
dto.setWebapps(other.getWebapps());
dto.setCamundaIntegration(other.getCamundaIntegration());
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\InternalsDto.java
| 1
|
请完成以下Java代码
|
public void setPortMapper(PortMapper portMapper) {
Assert.notNull(portMapper, "portMapper cannot be null");
this.portMapper = portMapper;
}
/**
* Use this {@link RequestMatcher} to narrow which requests are redirected to HTTPS.
*
* The filter already first checks for HTTPS in the uri scheme, so it is not necessary
* to include that check in this matcher.
* @param requestMatcher the {@link RequestMatcher} to use
*/
public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
private boolean isInsecure(HttpServletRequest request) {
return !"https".equals(request.getScheme());
}
|
private String createRedirectUri(HttpServletRequest request) {
String url = UrlUtils.buildFullRequestUrl(request);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
UriComponents components = builder.build();
int port = components.getPort();
if (port > 0) {
Integer httpsPort = this.portMapper.lookupHttpsPort(port);
Assert.state(httpsPort != null, () -> "HTTP Port '" + port + "' does not have a corresponding HTTPS Port");
builder.port(httpsPort);
}
return builder.scheme("https").toUriString();
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\transport\HttpsRedirectFilter.java
| 1
|
请完成以下Java代码
|
public int getM_PriceList_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_Version_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcCreate (final @Nullable java.lang.String ProcCreate)
{
set_Value (COLUMNNAME_ProcCreate, ProcCreate);
}
@Override
public java.lang.String getProcCreate()
{
return get_ValueAsString(COLUMNNAME_ProcCreate);
}
@Override
public void setProcessed (final boolean Processed)
|
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList_Version.java
| 1
|
请完成以下Java代码
|
final class DefaultTransportGraphQlClientBuilder
extends AbstractGraphQlClientBuilder<DefaultTransportGraphQlClientBuilder> {
private final GraphQlTransport transport;
DefaultTransportGraphQlClientBuilder(GraphQlTransport transport) {
Assert.notNull(transport, "GraphQlTransport is required");
this.transport = transport;
}
@Override
public GraphQlClient build() {
GraphQlClient client = buildGraphQlClient(this.transport);
return new DefaultTransportGraphQlClient(client, this.transport, getBuilderInitializer());
}
/**
* Default GraphQL client with a given transport.
*/
private static class DefaultTransportGraphQlClient extends AbstractDelegatingGraphQlClient {
private final GraphQlTransport transport;
private final Consumer<AbstractGraphQlClientBuilder<?>> builderInitializer;
|
DefaultTransportGraphQlClient(
GraphQlClient graphQlClient, GraphQlTransport transport,
Consumer<AbstractGraphQlClientBuilder<?>> builderInitializer) {
super(graphQlClient);
Assert.notNull(transport, "GraphQlTransport is required");
Assert.notNull(builderInitializer, "'builderInitializer' is required");
this.transport = transport;
this.builderInitializer = builderInitializer;
}
@Override
public DefaultTransportGraphQlClientBuilder mutate() {
DefaultTransportGraphQlClientBuilder builder = new DefaultTransportGraphQlClientBuilder(this.transport);
this.builderInitializer.accept(builder);
return builder;
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultTransportGraphQlClientBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExternalWorkerJobFailureRequest {
@ApiModelProperty(value = "The id of the external worker that reports the failure. Must match the id of the worker who has most recently locked the job.", required = true)
protected String workerId;
@ApiModelProperty(value = "Error message for the failure", example = "Database not available")
protected String errorMessage;
@ApiModelProperty(value = "Details for the failure")
protected String errorDetails;
@ApiModelProperty(value = "The new number of retries. If not set it will be reduced by 1. If 0 the job will be moved ot the dead letter table and would no longer be available for acquiring.")
protected Integer retries;
@ApiModelProperty(value = "The timeout after which the job should be made available again. ISO-8601 duration format PnDTnHnMn.nS with days considered to be exactly 24 hours.",
dataType = "string", example = "PT20M")
protected Duration retryTimeout;
public String getWorkerId() {
return workerId;
}
public void setWorkerId(String workerId) {
this.workerId = workerId;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
|
this.errorMessage = errorMessage;
}
public String getErrorDetails() {
return errorDetails;
}
public void setErrorDetails(String errorDetails) {
this.errorDetails = errorDetails;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public Duration getRetryTimeout() {
return retryTimeout;
}
public void setRetryTimeout(Duration retryTimeout) {
this.retryTimeout = retryTimeout;
}
}
|
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\acquire\ExternalWorkerJobFailureRequest.java
| 2
|
请完成以下Java代码
|
public class Customer {
private Person person;
private String city;
private Phone homePhone;
private Phone officePhone;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Phone getHomePhone() {
|
return homePhone;
}
public void setHomePhone(Phone homePhone) {
this.homePhone = homePhone;
}
public Phone getOfficePhone() {
return officePhone;
}
public void setOfficePhone(Phone officePhone) {
this.officePhone = officePhone;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xml\jibx\Customer.java
| 1
|
请完成以下Java代码
|
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public org.compiere.model.I_M_Allergen getM_Allergen()
{
return get_ValueAsPO(COLUMNNAME_M_Allergen_ID, org.compiere.model.I_M_Allergen.class);
}
@Override
public void setM_Allergen(final org.compiere.model.I_M_Allergen M_Allergen)
{
set_ValueFromPO(COLUMNNAME_M_Allergen_ID, org.compiere.model.I_M_Allergen.class, M_Allergen);
}
@Override
public void setM_Allergen_ID (final int M_Allergen_ID)
{
if (M_Allergen_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_M_Allergen_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Allergen_ID, M_Allergen_ID);
}
@Override
public int getM_Allergen_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Allergen_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen_Trl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getDataDirectory() {
return this.dataDirectory;
}
public void setDataDirectory(@Nullable String dataDirectory) {
this.dataDirectory = dataDirectory;
}
public String[] getQueues() {
return this.queues;
}
public void setQueues(String[] queues) {
this.queues = queues;
}
public String[] getTopics() {
return this.topics;
}
public void setTopics(String[] topics) {
this.topics = topics;
}
public String getClusterPassword() {
return this.clusterPassword;
}
public void setClusterPassword(String clusterPassword) {
|
this.clusterPassword = clusterPassword;
this.defaultClusterPassword = false;
}
public boolean isDefaultClusterPassword() {
return this.defaultClusterPassword;
}
/**
* Creates the minimal transport parameters for an embedded transport
* configuration.
* @return the transport parameters
* @see TransportConstants#SERVER_ID_PROP_NAME
*/
public Map<String, Object> generateTransportParameters() {
Map<String, Object> parameters = new HashMap<>();
parameters.put(TransportConstants.SERVER_ID_PROP_NAME, getServerId());
return parameters;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisProperties.java
| 2
|
请完成以下Java代码
|
public void setPA_GoalParent_ID (int PA_GoalParent_ID)
{
if (PA_GoalParent_ID < 1)
set_Value (COLUMNNAME_PA_GoalParent_ID, null);
else
set_Value (COLUMNNAME_PA_GoalParent_ID, Integer.valueOf(PA_GoalParent_ID));
}
/** Get Parent Goal.
@return Parent Goal
*/
public int getPA_GoalParent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_GoalParent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Measure getPA_Measure() throws RuntimeException
{
return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name)
.getPO(getPA_Measure_ID(), get_TrxName()); }
/** Set Measure.
@param PA_Measure_ID
Concrete Performance Measurement
*/
public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_Value (COLUMNNAME_PA_Measure_ID, null);
else
set_Value (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Relative Weight.
@param RelativeWeight
Relative weight of this step (0 = ignored)
*/
|
public void setRelativeWeight (BigDecimal RelativeWeight)
{
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
}
/** Get Relative Weight.
@return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Goal.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=8888
spring.cloud.config.server.git.uri=
spring.cloud.config.server.git.clone-on-start=true
spring.security.user.name=root
spring.security.user.password=s3cr3t
encrypt.keyStore.location=classpath:/config-server.jks
encrypt.keyStor
|
e.password=my-s70r3-s3cr3t
encrypt.keyStore.alias=config-server-key
encrypt.keyStore.secret=my-k34-s3cr3t
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-config\spring-cloud-config-server\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable ShowSummary getShowSummary() {
return this.showSummary;
}
public void setShowSummary(@Nullable ShowSummary showSummary) {
this.showSummary = showSummary;
}
public @Nullable ShowSummaryOutput getShowSummaryOutput() {
return this.showSummaryOutput;
}
public void setShowSummaryOutput(@Nullable ShowSummaryOutput showSummaryOutput) {
this.showSummaryOutput = showSummaryOutput;
}
public @Nullable UiService getUiService() {
return this.uiService;
}
public void setUiService(@Nullable UiService uiService) {
this.uiService = uiService;
}
public @Nullable Boolean getAnalyticsEnabled() {
return this.analyticsEnabled;
}
public void setAnalyticsEnabled(@Nullable Boolean analyticsEnabled) {
this.analyticsEnabled = analyticsEnabled;
}
public @Nullable String getLicenseKey() {
return this.licenseKey;
}
public void setLicenseKey(@Nullable String licenseKey) {
this.licenseKey = licenseKey;
}
/**
* Enumeration of types of summary to show. Values are the same as those on
* {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum
* is not used directly.
*/
public enum ShowSummary {
/**
* Do not show a summary.
*/
OFF,
/**
* Show a summary.
|
*/
SUMMARY,
/**
* Show a verbose summary.
*/
VERBOSE
}
/**
* Enumeration of destinations to which the summary should be output. Values are the
* same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards
* compatibility, the Liquibase enum is not used directly.
*/
public enum ShowSummaryOutput {
/**
* Log the summary.
*/
LOG,
/**
* Output the summary to the console.
*/
CONSOLE,
/**
* Log the summary and output it to the console.
*/
ALL
}
/**
* Enumeration of types of UIService. Values are the same as those on
* {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is
* not used directly.
*/
public enum UiService {
/**
* Console-based UIService.
*/
CONSOLE,
/**
* Logging-based UIService.
*/
LOGGER
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public GroupResponse createGroupResponse(Group group) {
return createGroupResponse(group, createUrlBuilder());
}
public GroupResponse createGroupResponse(Group group, RestUrlBuilder urlBuilder) {
GroupResponse response = new GroupResponse();
response.setId(group.getId());
response.setName(group.getName());
response.setType(group.getType());
return response;
}
public MembershipResponse createMembershipResponse(String userId, String groupId) {
return createMembershipResponse(userId, groupId, createUrlBuilder());
}
public MembershipResponse createMembershipResponse(String userId, String groupId, RestUrlBuilder urlBuilder) {
MembershipResponse response = new MembershipResponse();
response.setGroupId(groupId);
response.setUserId(userId);
return response;
}
public List<PrivilegeResponse> createPrivilegeResponseList(List<Privilege> privileges) {
List<PrivilegeResponse> responseList = new ArrayList<>(privileges.size());
for (Privilege privilege : privileges) {
responseList.add(createPrivilegeResponse(privilege));
}
return responseList;
}
public PrivilegeResponse createPrivilegeResponse(Privilege privilege) {
return new PrivilegeResponse(privilege.getId(), privilege.getName());
|
}
public PrivilegeResponse createPrivilegeResponse(Privilege privilege, List<User> users, List<Group> groups) {
PrivilegeResponse response = createPrivilegeResponse(privilege);
List<UserResponse> userResponses = new ArrayList<>(users.size());
for (User user : users) {
userResponses.add(createUserResponse(user, false));
}
response.setUsers(userResponses);
List<GroupResponse> groupResponses = new ArrayList<>(groups.size());
for (Group group : groups) {
groupResponses.add(createGroupResponse(group));
}
response.setGroups(groupResponses);
return response;
}
protected RestUrlBuilder createUrlBuilder() {
return RestUrlBuilder.fromCurrentRequest();
}
}
|
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\IdmRestResponseFactory.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setVATaxID(String value) {
this.vaTaxID = value;
}
/**
* Gets the value of the referenceNo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferenceNo() {
return referenceNo;
}
/**
* Sets the value of the referenceNo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenceNo(String value) {
this.referenceNo = value;
}
/**
* Gets the value of the setupPlaceNo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSetupPlaceNo() {
return setupPlaceNo;
}
/**
* Sets the value of the setupPlaceNo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSetupPlaceNo(String value) {
this.setupPlaceNo = value;
}
/**
* Gets the value of the siteName property.
*
|
* @return
* possible object is
* {@link String }
*
*/
public String getSiteName() {
return siteName;
}
/**
* Sets the value of the siteName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSiteName(String value) {
this.siteName = value;
}
/**
* Gets the value of the contact property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContact() {
return contact;
}
/**
* Sets the value of the contact property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContact(String value) {
this.contact = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop119VType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class AdColumnId implements RepoIdAware
{
@JsonCreator
public static AdColumnId ofRepoId(final int repoId)
{
return new AdColumnId(repoId);
}
public static AdColumnId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new AdColumnId(repoId) : null;
}
public static int toRepoId(final AdColumnId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
private AdColumnId(final int repoId)
{
|
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Column_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final AdColumnId id1, @Nullable final AdColumnId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\AdColumnId.java
| 2
|
请完成以下Java代码
|
default void nack(Duration sleep) {
throw new UnsupportedOperationException("nack(sleep) is not supported by this Acknowledgment");
}
/**
* Acknowledge the record at an index in the batch - commit the offset(s) of records
* in the batch up to and including the index. Requires
* {@link AckMode#MANUAL_IMMEDIATE}. The index must be greater than any previous
* partial batch acknowledgment index for this batch and in the range of the record
* list. This method must be called on the listener thread.
* @param index the index of the record to acknowledge.
* @since 3.0.10
*/
default void acknowledge(int index) {
throw new UnsupportedOperationException("ack(index) is not supported by this Acknowledgment");
}
/**
* Negatively acknowledge the record at an index in a batch - commit the offset(s) of
* records before the index and re-seek the partitions so that the record at the index
* and subsequent records will be redelivered after the sleep duration.
* Must be called on the consumer thread.
|
* <p>
* @param index the index of the failed record in the batch.
* @param sleep the duration to sleep; the actual sleep time will be larger of this value
* and the container's {@code pollTimeout}, which defaults to 5 seconds.
* @since 2.8.7
*/
default void nack(int index, Duration sleep) {
throw new UnsupportedOperationException("nack(index, sleep) is not supported by this Acknowledgment");
}
default boolean isOutOfOrderCommit() {
return false;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\Acknowledgment.java
| 1
|
请完成以下Java代码
|
public void onCancel()
{
dispose();
};
@Override
public void onOpenAsNewRecord()
{
dispose();
};
};
Find(final FindPanelBuilder builder)
{
super(builder.getParentFrame(),
Services.get(IMsgBL.class).getMsg(Env.getCtx(), "Find") + ": " + builder.getTitle(),
true // modal=true
);
findPanel = builder.buildFindPanel();
// metas: tsa: begin
if (findPanel.isDisposed())
{
this.dispose();
return;
}
findPanel.setActionListener(findPanelActionListener);
// Set panel size
// NOTE: we are setting such a big width because the table from advanced panel shall be displayed nicely.
final int findPanelHeight = AdempierePLAF.getInt(FindPanelUI.KEY_Dialog_Height, FindPanelUI.DEFAULT_Dialog_Height);
findPanel.setPreferredSize(new Dimension(950, findPanelHeight));
setIconImage(Images.getImage2("Find24"));
this.setContentPane(findPanel);
// teo_sarca, [ 1670847 ] Find dialog: closing and canceling need same
// functionality
this.addWindowListener(new WindowAdapter()
{
@Override
|
public void windowOpened(WindowEvent e)
{
findPanel.requestFocus();
}
@Override
public void windowClosing(WindowEvent e)
{
findPanel.doCancel();
}
});
AEnv.showCenterWindow(builder.getParentFrame(), this);
} // Find
@Override
public void dispose()
{
findPanel.dispose();
removeAll();
super.dispose();
} // dispose
/**************************************************************************
* Get Query - Retrieve result
*
* @return String representation of query
*/
public MQuery getQuery()
{
return findPanel.getQuery();
} // getQuery
/**
* @return true if cancel button pressed
*/
public boolean isCancel()
{
return findPanel.isCancel();
}
} // Find
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\Find.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDate dateCreated) {
this.dateCreated = dateCreated;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
|
this.status = status;
}
public List<OrderProduct> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(List<OrderProduct> orderProducts) {
this.orderProducts = orderProducts;
}
@Transient
public int getNumberOfProducts() {
return this.orderProducts.size();
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\Order.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(str);
}
});
}
/**
* 订单通知
*
* @param merchantOrderNo
*/
@Override
public void orderSend(String bankOrderNo) {
final String orderNo = bankOrderNo;
jmsTemplate.setDefaultDestinationName(MqConfig.ORDER_NOTIFY_QUEUE);
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(orderNo);
}
});
}
/**
* 通过ID获取通知记录
*
* @param id
* @return
*/
@Override
public RpNotifyRecord getNotifyRecordById(String id) {
return rpNotifyRecordDao.getById(id);
}
/**
* 根据商户编号,商户订单号,通知类型获取通知记录
*
* @param merchantNo
* 商户编号
* @param merchantOrderNo
* 商户订单号
* @param notifyType
* 消息类型
* @return
*/
@Override
public RpNotifyRecord getNotifyByMerchantNoAndMerchantOrderNoAndNotifyType(String merchantNo,
|
String merchantOrderNo, String notifyType) {
return rpNotifyRecordDao.getNotifyByMerchantNoAndMerchantOrderNoAndNotifyType(merchantNo, merchantOrderNo,
notifyType);
}
@Override
public PageBean<RpNotifyRecord> queryNotifyRecordListPage(PageParam pageParam, Map<String, Object> paramMap) {
return rpNotifyRecordDao.listPage(pageParam, paramMap);
}
/**
* 创建消息通知
*
* @param rpNotifyRecord
*/
@Override
public long createNotifyRecord(RpNotifyRecord rpNotifyRecord) {
return rpNotifyRecordDao.insert(rpNotifyRecord);
}
/**
* 修改消息通知
*
* @param rpNotifyRecord
*/
@Override
public void updateNotifyRecord(RpNotifyRecord rpNotifyRecord) {
rpNotifyRecordDao.update(rpNotifyRecord);
}
/**
* 创建消息通知记录
*
* @param rpNotifyRecordLog
* @return
*/
@Override
public long createNotifyRecordLog(RpNotifyRecordLog rpNotifyRecordLog) {
return rpNotifyRecordLogDao.insert(rpNotifyRecordLog);
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\service\impl\RpNotifyServiceImpl.java
| 2
|
请完成以下Java代码
|
public String getPostLogoutRedirectUri() {
return postLogoutRedirectUri;
}
public void setPostLogoutRedirectUri(String postLogoutRedirectUri) {
this.postLogoutRedirectUri = postLogoutRedirectUri;
}
}
public static class OAuth2IdentityProviderProperties {
/**
* Enable {@link OAuth2IdentityProvider}. Default {@code true}.
*/
private boolean enabled = true;
/**
* Name of the attribute (claim) that holds the groups.
*/
private String groupNameAttribute;
/**
* Group name attribute delimiter. Only used if the {@link #groupNameAttribute} is a {@link String}.
*/
private String groupNameDelimiter = ",";
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getGroupNameAttribute() {
return groupNameAttribute;
}
public void setGroupNameAttribute(String groupNameAttribute) {
this.groupNameAttribute = groupNameAttribute;
}
|
public String getGroupNameDelimiter() {
return groupNameDelimiter;
}
public void setGroupNameDelimiter(String groupNameDelimiter) {
this.groupNameDelimiter = groupNameDelimiter;
}
}
public OAuth2SSOLogoutProperties getSsoLogout() {
return ssoLogout;
}
public void setSsoLogout(OAuth2SSOLogoutProperties ssoLogout) {
this.ssoLogout = ssoLogout;
}
public OAuth2IdentityProviderProperties getIdentityProvider() {
return identityProvider;
}
public void setIdentityProvider(OAuth2IdentityProviderProperties identityProvider) {
this.identityProvider = identityProvider;
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\OAuth2Properties.java
| 1
|
请完成以下Java代码
|
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final Set<Integer> productIds = getProductIds();
if (productIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
getResult().setRecordsToOpen(I_M_Product.Table_Name, getProductIds(), ProductPricingConditionsViewFactory.WINDOW_ID_STRING);
|
return MSG_OK;
}
private Set<Integer> getProductIds()
{
return streamSelectedRows()
.map(MaterialCockpitRow::getProductId)
.map(ProductId::toRepoId)
.filter(productId -> productId > 0)
.distinct()
.limit(2)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\process\MD_Cockpit_PricingConditions.java
| 1
|
请完成以下Java代码
|
public void messageEventReceivedAsync(String messageName, String executionId) {
commandExecutor.execute(new MessageEventReceivedCmd(messageName, executionId, true));
}
@Override
public void addEventListener(FlowableEventListener listenerToAdd) {
commandExecutor.execute(new AddEventListenerCommand(listenerToAdd));
}
@Override
public void addEventListener(FlowableEventListener listenerToAdd, FlowableEngineEventType... types) {
commandExecutor.execute(new AddEventListenerCommand(listenerToAdd, types));
}
@Override
public void removeEventListener(FlowableEventListener listenerToRemove) {
commandExecutor.execute(new RemoveEventListenerCommand(listenerToRemove));
}
@Override
public void dispatchEvent(FlowableEvent event) {
commandExecutor.execute(new DispatchEventCommand(event));
}
@Override
public void setProcessInstanceName(String processInstanceId, String name) {
commandExecutor.execute(new SetProcessInstanceNameCmd(processInstanceId, name));
}
@Override
public List<Event> getProcessInstanceEvents(String processInstanceId) {
return commandExecutor.execute(new GetProcessInstanceEventsCmd(processInstanceId));
|
}
@Override
public ProcessInstanceBuilder createProcessInstanceBuilder() {
return new ProcessInstanceBuilderImpl(this);
}
public ProcessInstance startProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.getProcessDefinitionId() != null
|| processInstanceBuilder.getProcessDefinitionKey() != null) {
return commandExecutor.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder));
} else if (processInstanceBuilder.getMessageName() != null) {
return commandExecutor.execute(new StartProcessInstanceByMessageCmd(processInstanceBuilder));
} else {
throw new ActivitiIllegalArgumentException(
"No processDefinitionId, processDefinitionKey nor messageName provided");
}
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\RuntimeServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class FileStorageService {
private final Path fileStorageLocation;
@Autowired
public FileStorageService(FileStorageProperties fileStorageProperties) {
this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
.toAbsolutePath().normalize();
try {
Files.createDirectories(this.fileStorageLocation);
} catch (Exception ex) {
throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
}
}
public String storeFile(MultipartFile file) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if(fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
|
// Copy file to the target location (Replacing existing file with the same name)
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
public Resource loadFileAsResource(String fileName) {
try {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if(resource.exists()) {
return resource;
} else {
throw new FileNotFoundException("File not found " + fileName);
}
} catch (MalformedURLException ex) {
throw new FileNotFoundException("File not found " + fileName, ex);
}
}
}
|
repos\Spring-Boot-Advanced-Projects-main\springboot-upload-download-file-rest-api-example\src\main\java\net\alanbinu\springboot\fileuploaddownload\service\FileStorageService.java
| 2
|
请完成以下Java代码
|
default String getSubject() {
return this.getClaimAsString(LogoutTokenClaimNames.SUB);
}
/**
* Returns the Audience(s) {@code (aud)} that this ID Token is intended for.
* @return the Audience(s) that this ID Token is intended for
*/
default List<String> getAudience() {
return this.getClaimAsStringList(LogoutTokenClaimNames.AUD);
}
/**
* Returns the time at which the ID Token was issued {@code (iat)}.
* @return the time at which the ID Token was issued
*/
default Instant getIssuedAt() {
return this.getClaimAsInstant(LogoutTokenClaimNames.IAT);
}
/**
* Returns a {@link Map} that identifies this token as a logout token
* @return the identifying {@link Map}
*/
default Map<String, Object> getEvents() {
return getClaimAsMap(LogoutTokenClaimNames.EVENTS);
|
}
/**
* Returns a {@code String} value {@code (sid)} representing the OIDC Provider session
* @return the value representing the OIDC Provider session
*/
default String getSessionId() {
return getClaimAsString(LogoutTokenClaimNames.SID);
}
/**
* Returns the JWT ID {@code (jti)} claim which provides a unique identifier for the
* JWT.
* @return the JWT ID claim which provides a unique identifier for the JWT
*/
default String getId() {
return this.getClaimAsString(LogoutTokenClaimNames.JTI);
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\logout\LogoutTokenClaimAccessor.java
| 1
|
请完成以下Java代码
|
public Rate3 getRate() {
return rate;
}
/**
* Sets the value of the rate property.
*
* @param value
* allowed object is
* {@link Rate3 }
*
*/
public void setRate(Rate3 value) {
this.rate = value;
}
/**
* Gets the value of the frToDt property.
*
* @return
* possible object is
* {@link DateTimePeriodDetails }
*
*/
public DateTimePeriodDetails getFrToDt() {
return frToDt;
}
/**
* Sets the value of the frToDt property.
*
* @param value
* allowed object is
* {@link DateTimePeriodDetails }
*
*/
public void setFrToDt(DateTimePeriodDetails value) {
this.frToDt = value;
}
/**
* Gets the value of the rsn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRsn() {
|
return rsn;
}
/**
* Sets the value of the rsn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRsn(String value) {
this.rsn = value;
}
/**
* Gets the value of the tax property.
*
* @return
* possible object is
* {@link TaxCharges2 }
*
*/
public TaxCharges2 getTax() {
return tax;
}
/**
* Sets the value of the tax property.
*
* @param value
* allowed object is
* {@link TaxCharges2 }
*
*/
public void setTax(TaxCharges2 value) {
this.tax = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\InterestRecord1.java
| 1
|
请完成以下Java代码
|
public void assertBasePricingIsValid(final I_M_PriceList priceList)
{
final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class);
// final PriceListVersionId basePriceListVersionId = priceListsRepo.getBasePriceListVersionIdForPricingCalculationOrNull(plv);
// if (basePriceListVersionId != null)
// {
final int basePriceListId = priceList.getBasePriceList_ID();
if (basePriceListId <= 0)
{
// nothing to do
return;
}
final I_M_PriceList basePriceList = priceListsRepo.getById(basePriceListId);
//
final CurrencyId baseCurrencyId = CurrencyId.ofRepoId(basePriceList.getC_Currency_ID());
final CurrencyId currencyId = CurrencyId.ofRepoId(priceList.getC_Currency_ID());
if (!CurrencyId.equals(baseCurrencyId, currencyId))
{
throw new AdempiereException("@PriceListAndBasePriceListCurrencyMismatchError@")
.markAsUserValidationError();
}
|
final CountryId baseCountryId = CountryId.ofRepoIdOrNull(basePriceList.getC_Country_ID());
final CountryId countryId = CountryId.ofRepoIdOrNull(priceList.getC_Country_ID());
if (!CountryId.equals(baseCountryId, countryId))
{
throw new AdempiereException("@PriceListAndBasePriceListCountryMismatchError@")
.markAsUserValidationError();
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_M_PriceList.COLUMNNAME_Name })
public void updatePLVName(@NonNull final I_M_PriceList priceList)
{
final IPriceListBL priceListBL = Services.get(IPriceListBL.class);
priceListBL.updateAllPLVName(priceList.getName(), PriceListId.ofRepoId(priceList.getM_PriceList_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\interceptor\M_PriceList.java
| 1
|
请完成以下Java代码
|
public BankTransactionCodeStructure5 getDomn() {
return domn;
}
/**
* Sets the value of the domn property.
*
* @param value
* allowed object is
* {@link BankTransactionCodeStructure5 }
*
*/
public void setDomn(BankTransactionCodeStructure5 value) {
this.domn = value;
}
/**
* Gets the value of the prtry property.
*
* @return
* possible object is
* {@link ProprietaryBankTransactionCodeStructure1 }
|
*
*/
public ProprietaryBankTransactionCodeStructure1 getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link ProprietaryBankTransactionCodeStructure1 }
*
*/
public void setPrtry(ProprietaryBankTransactionCodeStructure1 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\BankTransactionCodeStructure4.java
| 1
|
请完成以下Java代码
|
public class ProductHelperWithEventListener {
final Logger LOGGER = LoggerFactory.getLogger(ProductHelperWithEventListener.class);
private Cache<String, Integer> cachedDiscounts;
private int cacheMissCount = 0;
public ProductHelperWithEventListener() {
cachedDiscounts = Cache2kBuilder.of(String.class, Integer.class)
.name("discount-listener")
.expireAfterWrite(10, TimeUnit.MILLISECONDS)
.entryCapacity(100)
.loader((key) -> {
cacheMissCount++;
return "Sports".equalsIgnoreCase(key) ? 20 : 10;
})
.addListener(new CacheEntryCreatedListener<String, Integer>() {
@Override
public void onEntryCreated(Cache<String, Integer> cache, CacheEntry<String, Integer> entry) {
|
LOGGER.info("Entry created: [{}, {}].", entry.getKey(), entry.getValue());
}
})
.build();
}
public Integer getDiscount(String productType) {
return cachedDiscounts.get(productType);
}
public int getCacheMissCount() {
return cacheMissCount;
}
}
|
repos\tutorials-master\libraries-data-3\src\main\java\com\baeldung\cache2k\ProductHelperWithEventListener.java
| 1
|
请完成以下Java代码
|
public LookupValue getToByUserId(final Integer adUserId)
{
return emailToLookup.findById(adUserId);
}
@ToString
private static final class WebuiEmailEntry
{
private WebuiEmail email;
public WebuiEmailEntry(@NonNull final WebuiEmail email)
{
this.email = email;
}
public synchronized WebuiEmail getEmail()
{
return email;
}
public synchronized WebuiEmailChangeResult compute(final UnaryOperator<WebuiEmail> modifier)
{
final WebuiEmail emailOld = email;
final WebuiEmail emailNew = modifier.apply(emailOld);
if (emailNew == null)
{
|
throw new NullPointerException("email");
}
email = emailNew;
return WebuiEmailChangeResult.builder().email(emailNew).originalEmail(emailOld).build();
}
}
@Value
@AllArgsConstructor
public static class WebuiEmailRemovedEvent
{
@NonNull WebuiEmail email;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\WebuiMailRepository.java
| 1
|
请完成以下Java代码
|
public boolean isPossibleHighVolume(final int highVolumeThreshold)
{
final Integer estimatedSize = estimateSize();
return estimatedSize == null || estimatedSize > highVolumeThreshold;
}
@Nullable
private Integer estimateSize()
{
return getFixedHUIds().map(HuIdsFilterList::estimateSize).orElse(null);
}
interface CaseConverter<T>
{
T acceptAll();
T acceptAllBut(@NonNull Set<HuId> alwaysIncludeHUIds, @NonNull Set<HuId> excludeHUIds);
T acceptNone();
T acceptOnly(@NonNull HuIdsFilterList fixedHUIds, @NonNull Set<HuId> alwaysIncludeHUIds);
T huQuery(@NonNull IHUQueryBuilder initialHUQueryCopy, @NonNull Set<HuId> alwaysIncludeHUIds, @NonNull Set<HuId> excludeHUIds);
}
public synchronized <T> T convert(@NonNull final CaseConverter<T> converter)
{
if (initialHUQuery == null)
{
if (initialHUIds == null)
{
throw new IllegalStateException("initialHUIds shall not be null for " + this);
}
else if (initialHUIds.isAll())
{
if (mustHUIds.isEmpty() && shallNotHUIds.isEmpty())
{
return converter.acceptAll();
}
else
{
return converter.acceptAllBut(ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds));
}
}
else
{
final ImmutableSet<HuId> fixedHUIds = Stream.concat(
initialHUIds.stream(),
|
mustHUIds.stream())
.distinct()
.filter(huId -> !shallNotHUIds.contains(huId)) // not excluded
.collect(ImmutableSet.toImmutableSet());
if (fixedHUIds.isEmpty())
{
return converter.acceptNone();
}
else
{
return converter.acceptOnly(HuIdsFilterList.of(fixedHUIds), ImmutableSet.copyOf(mustHUIds));
}
}
}
else
{
return converter.huQuery(initialHUQuery.copy(), ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterData.java
| 1
|
请完成以下Java代码
|
public ValueNamePair getSelectedLook()
{
return lookList.getSelectedValue();
}
/**
* Get theme selected by user
* @return selected theme
*/
public ValueNamePair getSelectedTheme()
{
return themeList.getSelectedValue();
}
/** Sets the action listener for "Edit UI defaults" button */
public PLAFEditorPanel setOnEditUIDefaultsActionListener(final ActionListener editUIDefaultsActionListener)
{
this.editUIDefaultsActionListener = editUIDefaultsActionListener;
return this;
}
}
/**
* Glass pane to block input and mouse event from the preview components
* @author Low Heng Sin
*/
class GlassPane extends JComponent
{
private static final long serialVersionUID = -4416920279272513L;
GlassPane()
{
addMouseListener(new MouseAdapter()
{
});
addKeyListener(new KeyAdapter()
{
});
addFocusListener(new FocusAdapter()
{
});
}
}
/**
* A custom panel, only repaint when look and feel or theme changed.
* @author Low Heng Sin
*/
class PreviewPanel extends CPanel
{
/**
*
*/
private static final long serialVersionUID = 6028614986952449622L;
|
private boolean capture = true;
private LookAndFeel laf = null;
private MetalTheme theme = null;
private BufferedImage image;
@Override
public void paint(Graphics g)
{
if (capture) {
//capture preview image
image = (BufferedImage)createImage(this.getWidth(),this.getHeight());
super.paint(image.createGraphics());
g.drawImage(image, 0, 0, null);
capture = false;
if (laf != null)
{
//reset to original setting
if (laf instanceof MetalLookAndFeel)
AdempierePLAF.setCurrentMetalTheme((MetalLookAndFeel)laf, theme);
try {
UIManager.setLookAndFeel(laf);
} catch (UnsupportedLookAndFeelException e) {
}
laf = null;
theme = null;
}
} else {
//draw captured preview image
if (image != null)
g.drawImage(image, 0, 0, null);
}
}
/**
* Refresh look and feel preview, reset to original setting after
* refresh.
* @param currentLaf Current Look and feel
* @param currentTheme Current Theme
*/
void refresh(LookAndFeel currentLaf, MetalTheme currentTheme)
{
this.laf = currentLaf;
this.theme = currentTheme;
capture = true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\PLAFEditorPanel.java
| 1
|
请完成以下Java代码
|
private @Nullable O createOperation(EndpointId endpointId, Object target, Method method) {
return OPERATION_TYPES.entrySet()
.stream()
.map((entry) -> createOperation(endpointId, target, method, entry.getKey(), entry.getValue()))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
}
private @Nullable O createOperation(EndpointId endpointId, Object target, Method method,
OperationType operationType, Class<? extends Annotation> annotationType) {
MergedAnnotation<?> annotation = MergedAnnotations.from(method).get(annotationType);
if (!annotation.isPresent()) {
return null;
}
DiscoveredOperationMethod operationMethod = new DiscoveredOperationMethod(method, operationType,
annotation.asAnnotationAttributes());
OperationInvoker invoker = new ReflectiveOperationInvoker(target, operationMethod, this.parameterValueMapper);
invoker = applyAdvisors(endpointId, operationMethod, invoker);
return createOperation(endpointId, operationMethod, invoker);
}
|
private OperationInvoker applyAdvisors(EndpointId endpointId, OperationMethod operationMethod,
OperationInvoker invoker) {
if (this.invokerAdvisors != null) {
for (OperationInvokerAdvisor advisor : this.invokerAdvisors) {
invoker = advisor.apply(endpointId, operationMethod.getOperationType(), operationMethod.getParameters(),
invoker);
}
}
return invoker;
}
protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod,
OperationInvoker invoker);
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\annotation\DiscoveredOperationsFactory.java
| 1
|
请完成以下Java代码
|
public void beforeSave(final I_PP_Order_Weighting_Run record)
{
if (InterfaceWrapperHelper.isUIAction(record))
{
final boolean isUOMChanged = InterfaceWrapperHelper.isValueChanged(record, I_PP_Order_Weighting_Run.COLUMNNAME_C_UOM_ID);
if (InterfaceWrapperHelper.isValueChanged(record, I_PP_Order_Weighting_Run.COLUMNNAME_TargetWeight)
|| InterfaceWrapperHelper.isValueChanged(record, I_PP_Order_Weighting_Run.COLUMNNAME_Tolerance_Perc)
|| isUOMChanged)
{
ppOrderWeightingRunRepository.updateWhileSaving(
record,
weightingRun -> {
if (isUOMChanged)
{
weightingRun.updateUOMFromHeaderToChecks();
}
|
weightingRun.updateTargetWeightRange();
}
);
}
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void beforeDelete(final I_PP_Order_Weighting_Run record)
{
final PPOrderWeightingRunId weightingRunId = PPOrderWeightingRunId.ofRepoId(record.getPP_Order_Weighting_Run_ID());
ppOrderWeightingRunRepository.deleteChecks(weightingRunId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\interceptor\PP_Order_Weighting_Run.java
| 1
|
请完成以下Java代码
|
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public List<String> getImageUrls() {
return imageUrls;
}
public void setImageUrls(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
public List<String> getVideoUrls() {
return videoUrls;
}
public void setVideoUrls(List<String> videoUrls) {
this.videoUrls = videoUrls;
}
|
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public Float getAverageRating() {
return averageRating;
}
public void setAverageRating(Float averageRating) {
this.averageRating = averageRating;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\entity\Product.java
| 1
|
请完成以下Java代码
|
private static QuickInputDescriptorKey createQuickInputDescriptorKey(final DocumentEntityDescriptor includedDocumentDescriptor)
{
return QuickInputDescriptorKey.builder()
.documentType(includedDocumentDescriptor.getDocumentType()) // i.e. Window
.documentTypeId(includedDocumentDescriptor.getDocumentTypeId()) // i.e. AD_Window_ID
.includedTableName(Optional.ofNullable(includedDocumentDescriptor.getTableNameOrNull()))
.includedTabId(Check.assumeNotNull(includedDocumentDescriptor.getDetailId(), "Entity shall be included tab: {}", includedDocumentDescriptor))
.soTrx(includedDocumentDescriptor.getSOTrx())
.build();
}
private QuickInputDescriptor getQuickInputEntityDescriptorOrNull(final QuickInputDescriptorKey key)
{
return descriptors.getOrLoad(key, this::createQuickInputDescriptorOrNull);
}
private QuickInputDescriptor createQuickInputDescriptorOrNull(final QuickInputDescriptorKey key)
{
final IQuickInputDescriptorFactory quickInputDescriptorFactory = getQuickInputDescriptorFactory(key);
if (quickInputDescriptorFactory == null)
{
return null;
}
return quickInputDescriptorFactory.createQuickInputDescriptor(
key.getDocumentType(),
key.getDocumentTypeId(),
key.getIncludedTabId(),
key.getSoTrx());
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final QuickInputDescriptorKey key)
{
return getQuickInputDescriptorFactory(
//
// factory for included document:
IQuickInputDescriptorFactory.MatchingKey.includedDocument(
key.getDocumentType(),
key.getDocumentTypeId(),
key.getIncludedTableName().orElse(null)),
//
// factory for table:
IQuickInputDescriptorFactory.MatchingKey.ofTableName(key.getIncludedTableName().orElse(null)));
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final IQuickInputDescriptorFactory.MatchingKey... matchingKeys)
{
for (final IQuickInputDescriptorFactory.MatchingKey matchingKey : matchingKeys)
{
final IQuickInputDescriptorFactory factory = getQuickInputDescriptorFactory(matchingKey);
if (factory != null)
{
return factory;
}
}
|
return null;
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final IQuickInputDescriptorFactory.MatchingKey matchingKey)
{
final ImmutableList<IQuickInputDescriptorFactory> matchingFactories = factories.get(matchingKey);
if (matchingFactories.isEmpty())
{
return null;
}
if (matchingFactories.size() > 1)
{
logger.warn("More than one factory found for {}. Using the first one.", matchingFactories);
}
return matchingFactories.get(0);
}
@lombok.Builder
@lombok.Value
private static class QuickInputDescriptorKey
{
@NonNull DocumentType documentType;
@NonNull DocumentId documentTypeId;
@NonNull Optional<String> includedTableName;
@NonNull DetailId includedTabId;
@NonNull Optional<SOTrx> soTrx;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputDescriptorFactoryService.java
| 1
|
请完成以下Java代码
|
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO(Properties ctx)
{
POInfo poi = POInfo.getPOInfo(ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer("X_M_PackagingTreeItemSched[")
.append(get_ID()).append("]");
return sb.toString();
}
/**
* Set Packaging Tree Item Schedule.
*
* @param M_PackagingTreeItemSched_ID
* Packaging Tree Item Schedule
*/
public void setM_PackagingTreeItemSched_ID(int M_PackagingTreeItemSched_ID)
{
if (M_PackagingTreeItemSched_ID < 1)
set_ValueNoCheck(COLUMNNAME_M_PackagingTreeItemSched_ID, null);
else
set_ValueNoCheck(COLUMNNAME_M_PackagingTreeItemSched_ID, Integer.valueOf(M_PackagingTreeItemSched_ID));
}
/**
* Get Packaging Tree Item Schedule.
*
* @return Packaging Tree Item Schedule
*/
public int getM_PackagingTreeItemSched_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTreeItemSched_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_PackagingTreeItem getM_PackagingTreeItem() throws RuntimeException
{
return (I_M_PackagingTreeItem)MTable.get(getCtx(), I_M_PackagingTreeItem.Table_Name)
.getPO(getM_PackagingTreeItem_ID(), get_TrxName());
}
/**
* Set Packaging Tree Item.
*
* @param M_PackagingTreeItem_ID
* Packaging Tree Item
*/
public void setM_PackagingTreeItem_ID(int M_PackagingTreeItem_ID)
{
if (M_PackagingTreeItem_ID < 1)
set_Value(COLUMNNAME_M_PackagingTreeItem_ID, null);
else
set_Value(COLUMNNAME_M_PackagingTreeItem_ID, Integer.valueOf(M_PackagingTreeItem_ID));
}
/**
|
* Get Packaging Tree Item.
*
* @return Packaging Tree Item
*/
public int getM_PackagingTreeItem_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTreeItem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException
{
return (I_M_ShipmentSchedule)MTable.get(getCtx(), I_M_ShipmentSchedule.Table_Name)
.getPO(getM_ShipmentSchedule_ID(), get_TrxName());
}
@Override
public int getM_ShipmentSchedule_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipmentSchedule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public void setM_ShipmentSchedule_ID(int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value(COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value(COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID));
}
/**
* Set Menge.
*
* @param Qty
* Menge
*/
public void setQty(BigDecimal Qty)
{
set_Value(COLUMNNAME_Qty, Qty);
}
/**
* Get Menge.
*
* @return Menge
*/
public BigDecimal getQty()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTreeItemSched.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQtyOverride()
{
return InterfaceWrapperHelper.getValueOrNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override);
}
public BigDecimal getInitialSchedQtyDelivered()
{
return initialSchedQtyDelivered;
}
public void setShipmentScheduleLineNetAmt(final BigDecimal lineNetAmt)
{
shipmentSchedule.setLineNetAmt(lineNetAmt);
}
@Nullable
public String getSalesOrderPORef()
{
return salesOrder.map(I_C_Order::getPOReference).orElse(null);
}
|
@Nullable
public InputDataSourceId getSalesOrderADInputDatasourceID()
{
if(!salesOrder.isPresent())
{
return null;
}
final I_C_Order orderRecord = salesOrder.get();
return InputDataSourceId.ofRepoIdOrNull(orderRecord.getAD_InputDataSource_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\OlAndSched.java
| 1
|
请完成以下Java代码
|
public Integer getMode() {
return mode;
}
public ClusterServerModifyRequest setMode(Integer mode) {
this.mode = mode;
return this;
}
public ServerFlowConfig getFlowConfig() {
return flowConfig;
}
public ClusterServerModifyRequest setFlowConfig(
ServerFlowConfig flowConfig) {
this.flowConfig = flowConfig;
return this;
}
public ServerTransportConfig getTransportConfig() {
return transportConfig;
}
public ClusterServerModifyRequest setTransportConfig(
ServerTransportConfig transportConfig) {
this.transportConfig = transportConfig;
return this;
}
public Set<String> getNamespaceSet() {
return namespaceSet;
}
public ClusterServerModifyRequest setNamespaceSet(Set<String> namespaceSet) {
|
this.namespaceSet = namespaceSet;
return this;
}
@Override
public String toString() {
return "ClusterServerModifyRequest{" +
"app='" + app + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", mode=" + mode +
", flowConfig=" + flowConfig +
", transportConfig=" + transportConfig +
", namespaceSet=" + namespaceSet +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\request\ClusterServerModifyRequest.java
| 1
|
请完成以下Java代码
|
public void setCustomer(String customer) {
this.customer = customer;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValidUntil() {
return validUntil;
}
public void setValidUntil(String validUntil) {
this.validUntil = validUntil;
}
public Boolean isUnlimited() {
return isUnlimited;
}
public void setUnlimited(Boolean isUnlimited) {
this.isUnlimited = isUnlimited;
}
public Map<String, String> getFeatures() {
|
return features;
}
public void setFeatures(Map<String, String> features) {
this.features = features;
}
public String getRaw() {
return raw;
}
public void setRaw(String raw) {
this.raw = raw;
}
public static LicenseKeyDataDto fromEngineDto(LicenseKeyData other) {
return new LicenseKeyDataDto(
other.getCustomer(),
other.getType(),
other.getValidUntil(),
other.isUnlimited(),
other.getFeatures(),
other.getRaw());
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\LicenseKeyDataDto.java
| 1
|
请完成以下Java代码
|
public boolean supportsCustomEditor()
{
return true;
} // supportsCustomEditor
/**
* Register a listener for the PropertyChange event. When a
* PropertyEditor changes its value it should fire a PropertyChange
* event on all registered PropertyChangeListeners, specifying the
* null value for the property name and itself as the source.
*
* @param listener An object to be invoked when a PropertyChange
* event is fired.
*/
@Override
|
public void addPropertyChangeListener(PropertyChangeListener listener)
{
super.addPropertyChangeListener(listener);
} // addPropertyChangeListener
/**
* Remove a listener for the PropertyChange event.
*
* @param listener The PropertyChange listener to be removed.
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener listener)
{
super.removePropertyChangeListener(listener);
} // removePropertyChangeListener
} // AdempiereColorEditor
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\swing\ColorEditor.java
| 1
|
请完成以下Java代码
|
public GroupTemplateId getGroupTemplateId(@NonNull final GroupId groupId)
{
return queryBL
.createQueryBuilder(I_C_Order_CompensationGroup.class)
.addEqualsFilter(I_C_Order_CompensationGroup.COLUMNNAME_C_Order_CompensationGroup_ID, groupId.getOrderCompensationGroupId())
.andCollect(I_C_Order_CompensationGroup.COLUMNNAME_C_CompensationGroup_Schema_ID, I_C_CompensationGroup_Schema.class)
.create()
.firstIdOnly(GroupTemplateId::ofRepoIdOrNull);
}
public I_C_OrderLine createRegularLineFromTemplate(
@NonNull final GroupTemplateRegularLine from,
@NonNull final I_C_Order targetOrder,
final @NonNull RetrieveOrCreateGroupRequest request)
{
|
final I_C_OrderLine orderLine = orderLineBL.createOrderLine(targetOrder);
final ProductId productId = from.getProductId();
orderLine.setM_Product_ID(productId.getRepoId());
orderLine.setM_AttributeSetInstance_ID(AttributeSetInstanceId.NONE.getRepoId());
orderLine.setC_UOM_ID(from.getQty().getUomId().getRepoId());
orderLine.setQtyEntered(request.getQtyMultiplier().multiply(from.getQty().toBigDecimal()));
orderLine.setC_CompensationGroup_Schema_TemplateLine_ID(from.getId().getRepoId());
orderLine.setC_Flatrate_Conditions_ID(ConditionsId.toRepoId(request.getNewContractConditionsId()));
orderLine.setIsAllowSeparateInvoicing(from.isAllowSeparateInvoicing());
orderLine.setIsHideWhenPrinting(from.isHideWhenPrinting());
orderLineBL.save(orderLine);
return orderLine;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderGroupRepository.java
| 1
|
请完成以下Java代码
|
public PaymentRule getPaymentRule(final JsonOLCandCreateRequest request)
{
final JSONPaymentRule jsonPaymentRule = request.getPaymentRule();
if (jsonPaymentRule == null)
{
return null;
}
if (JSONPaymentRule.Paypal.equals(jsonPaymentRule))
{
return PaymentRule.PayPal;
}
if (JSONPaymentRule.OnCredit.equals(jsonPaymentRule))
{
return PaymentRule.OnCredit;
}
if (JSONPaymentRule.DirectDebit.equals(jsonPaymentRule))
{
return PaymentRule.DirectDebit;
}
throw MissingResourceException.builder()
.resourceName("paymentRule")
.resourceIdentifier(jsonPaymentRule.getCode())
.parentResource(request)
.build();
}
public PaymentTermId getPaymentTermId(@NonNull final JsonOLCandCreateRequest request, @NonNull final OrgId orgId)
{
final String paymentTermCode = request.getPaymentTerm();
if (Check.isEmpty(paymentTermCode))
{
return null;
|
}
final IdentifierString paymentTerm = IdentifierString.of(paymentTermCode);
final PaymentTermQueryBuilder queryBuilder = PaymentTermQuery.builder();
queryBuilder.orgId(orgId);
switch (paymentTerm.getType())
{
case EXTERNAL_ID:
queryBuilder.externalId(paymentTerm.asExternalId());
break;
case VALUE:
queryBuilder.value(paymentTerm.asValue());
break;
default:
throw new InvalidIdentifierException(paymentTerm);
}
final Optional<PaymentTermId> paymentTermId = paymentTermRepo.firstIdOnly(queryBuilder.build());
return paymentTermId.orElseThrow(() -> MissingResourceException.builder()
.resourceName("PaymentTerm")
.resourceIdentifier(paymentTermCode)
.parentResource(request).build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\MasterdataProvider.java
| 1
|
请完成以下Java代码
|
public boolean reActivateIt()
{
log.info(toString());
// Before reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REACTIVATE);
if (m_processMsg != null)
return false;
// After reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REACTIVATE);
if (m_processMsg != null)
return false;
return false;
} // reActivateIt
/*************************************************************************
* Get Summary
* @return Summary of Document
*/
@Override
public String getSummary()
{
StringBuffer sb = new StringBuffer();
sb.append(getDocumentNo());
// : Total Lines = 123.00 (#1)
sb.append(": ")
.append(Msg.translate(getCtx(),"ApprovalAmt")).append("=").append(getApprovalAmt())
.append(" (#").append(getLines(false).length).append(")");
// - Description
if (getDescription() != null && getDescription().length() > 0)
sb.append(" - ").append(getDescription());
return sb.toString();
} // getSummary
@Override
public LocalDate getDocumentDate()
{
return TimeUtil.asLocalDate(getCreated());
}
/**
* Get Process Message
|
* @return clear text error message
*/
@Override
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
* @return AD_User_ID
*/
@Override
public int getDoc_User_ID()
{
return getUpdatedBy();
} // getDoc_User_ID
/**
* Get Document Currency
* @return C_Currency_ID
*/
@Override
public int getC_Currency_ID()
{
// MPriceList pl = MPriceList.get(getCtx(), getM_PriceList_ID());
// return pl.getC_Currency_ID();
return 0;
} // getC_Currency_ID
} // MInOutConfirm
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInOutConfirm.java
| 1
|
请完成以下Java代码
|
public int getDPD_StoreOrder_Log_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DPD_StoreOrder_Log_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Duration (ms).
@param DurationMillis Duration (ms) */
@Override
public void setDurationMillis (int DurationMillis)
{
set_Value (COLUMNNAME_DurationMillis, Integer.valueOf(DurationMillis));
}
/** Get Duration (ms).
@return Duration (ms) */
@Override
public int getDurationMillis ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DurationMillis);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Fehler.
@param IsError
Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Fehler.
@return Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override
public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
|
return "Y".equals(oo);
}
return false;
}
/** Set Request Message.
@param RequestMessage Request Message */
@Override
public void setRequestMessage (java.lang.String RequestMessage)
{
set_Value (COLUMNNAME_RequestMessage, RequestMessage);
}
/** Get Request Message.
@return Request Message */
@Override
public java.lang.String getRequestMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestMessage);
}
/** Set Response Message.
@param ResponseMessage Response Message */
@Override
public void setResponseMessage (java.lang.String ResponseMessage)
{
set_Value (COLUMNNAME_ResponseMessage, ResponseMessage);
}
/** Get Response Message.
@return Response Message */
@Override
public java.lang.String getResponseMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponseMessage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrder_Log.java
| 1
|
请完成以下Java代码
|
protected String getBusinessKey(ActivityExecution execution) {
return getCallableElement().getBusinessKey(execution);
}
protected VariableMap getInputVariables(ActivityExecution callingExecution) {
return getCallableElement().getInputVariables(callingExecution);
}
protected VariableMap getOutputVariables(VariableScope calledElementScope) {
return getCallableElement().getOutputVariables(calledElementScope);
}
protected VariableMap getOutputVariablesLocal(VariableScope calledElementScope) {
return getCallableElement().getOutputVariablesLocal(calledElementScope);
}
protected Integer getVersion(ActivityExecution execution) {
return getCallableElement().getVersion(execution);
}
protected String getDeploymentId(ActivityExecution execution) {
return getCallableElement().getDeploymentId();
}
|
protected CallableElementBinding getBinding() {
return getCallableElement().getBinding();
}
protected boolean isLatestBinding() {
return getCallableElement().isLatestBinding();
}
protected boolean isDeploymentBinding() {
return getCallableElement().isDeploymentBinding();
}
protected boolean isVersionBinding() {
return getCallableElement().isVersionBinding();
}
protected abstract void startInstance(ActivityExecution execution, VariableMap variables, String businessKey);
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallableElementActivityBehavior.java
| 1
|
请完成以下Java代码
|
public void setIsTradeDiscountPosted (final boolean IsTradeDiscountPosted)
{
set_Value (COLUMNNAME_IsTradeDiscountPosted, IsTradeDiscountPosted);
}
@Override
public boolean isTradeDiscountPosted()
{
return get_ValueAsBoolean(COLUMNNAME_IsTradeDiscountPosted);
}
@Override
public org.compiere.model.I_M_CostType getM_CostType()
{
return get_ValueAsPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class);
}
@Override
public void setM_CostType(final org.compiere.model.I_M_CostType M_CostType)
{
set_ValueFromPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class, M_CostType);
}
@Override
public void setM_CostType_ID (final int M_CostType_ID)
{
if (M_CostType_ID < 1)
set_Value (COLUMNNAME_M_CostType_ID, null);
else
set_Value (COLUMNNAME_M_CostType_ID, M_CostType_ID);
}
@Override
public int getM_CostType_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostType_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPeriod_OpenFuture (final int Period_OpenFuture)
{
set_Value (COLUMNNAME_Period_OpenFuture, Period_OpenFuture);
}
@Override
public int getPeriod_OpenFuture()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenFuture);
}
@Override
public void setPeriod_OpenHistory (final int Period_OpenHistory)
{
set_Value (COLUMNNAME_Period_OpenHistory, Period_OpenHistory);
}
@Override
public int getPeriod_OpenHistory()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenHistory);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
|
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
/**
* TaxCorrectionType AD_Reference_ID=392
* Reference name: C_AcctSchema TaxCorrectionType
*/
public static final int TAXCORRECTIONTYPE_AD_Reference_ID=392;
/** None = N */
public static final String TAXCORRECTIONTYPE_None = "N";
/** Write_OffOnly = W */
public static final String TAXCORRECTIONTYPE_Write_OffOnly = "W";
/** DiscountOnly = D */
public static final String TAXCORRECTIONTYPE_DiscountOnly = "D";
/** Write_OffAndDiscount = B */
public static final String TAXCORRECTIONTYPE_Write_OffAndDiscount = "B";
@Override
public void setTaxCorrectionType (final java.lang.String TaxCorrectionType)
{
set_Value (COLUMNNAME_TaxCorrectionType, TaxCorrectionType);
}
@Override
public java.lang.String getTaxCorrectionType()
{
return get_ValueAsString(COLUMNNAME_TaxCorrectionType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema.java
| 1
|
请完成以下Java代码
|
public void setProcessInstanceName(String processInstanceId, String name) {
commandExecutor.execute(new SetProcessInstanceNameCmd(processInstanceId, name));
}
@Override
public List<Event> getProcessInstanceEvents(String processInstanceId) {
return commandExecutor.execute(new GetProcessInstanceEventsCmd(processInstanceId));
}
@Override
public List<FlowNode> getEnabledActivitiesFromAdhocSubProcess(String executionId) {
return commandExecutor.execute(new GetEnabledActivitiesForAdhocSubProcessCmd(executionId));
}
@Override
public Execution executeActivityInAdhocSubProcess(String executionId, String activityId) {
return commandExecutor.execute(new ExecuteActivityForAdhocSubProcessCmd(executionId, activityId));
}
@Override
public void completeAdhocSubProcess(String executionId) {
commandExecutor.execute(new CompleteAdhocSubProcessCmd(executionId));
}
@Override
public ProcessInstanceBuilder createProcessInstanceBuilder() {
return new ProcessInstanceBuilderImpl(this);
}
|
@Override
public ProcessInstance startCreatedProcessInstance(
ProcessInstance createdProcessInstance,
Map<String, Object> variables
) {
return commandExecutor.execute(new StartCreatedProcessInstanceCmd<>(createdProcessInstance, variables));
}
public ProcessInstance startProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.hasProcessDefinitionIdOrKey()) {
return commandExecutor.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder));
} else if (processInstanceBuilder.getMessageName() != null) {
return commandExecutor.execute(new StartProcessInstanceByMessageCmd(processInstanceBuilder));
} else {
throw new ActivitiIllegalArgumentException(
"No processDefinitionId, processDefinitionKey nor messageName provided"
);
}
}
public ProcessInstance createProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.hasProcessDefinitionIdOrKey()) {
return commandExecutor.execute(new CreateProcessInstanceCmd(processInstanceBuilder));
} else {
throw new ActivitiIllegalArgumentException(
"No processDefinitionId, processDefinitionKey nor messageName provided"
);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\RuntimeServiceImpl.java
| 1
|
请完成以下Java代码
|
private PackageLabels createPackageLabels(final Label.Sendung goPackageLabels)
{
final Label.Sendung.PDFs pdfs = goPackageLabels.getPDFs();
return PackageLabels.builder()
.orderId(GOUtils.createOrderId(goPackageLabels.getSendungsnummerAX4()))
.defaultLabelType(GOPackageLabelType.DIN_A6_ROUTER_LABEL)
.label(PackageLabel.builder()
.type(GOPackageLabelType.DIN_A4_HWB)
.fileName(GOPackageLabelType.DIN_A4_HWB.toString())
.contentType(PackageLabel.CONTENTTYPE_PDF)
.labelData(pdfs.getFrachtbrief())
.build())
.label(PackageLabel.builder()
.type(GOPackageLabelType.DIN_A6_ROUTER_LABEL)
.fileName(GOPackageLabelType.DIN_A6_ROUTER_LABEL.toString())
.contentType(PackageLabel.CONTENTTYPE_PDF)
.labelData(pdfs.getRouterlabel())
.build())
.label(PackageLabel.builder()
.type(GOPackageLabelType.DIN_A6_ROUTER_LABEL_ZEBRA)
.fileName(GOPackageLabelType.DIN_A6_ROUTER_LABEL_ZEBRA.toString())
.contentType(PackageLabel.CONTENTTYPE_PDF)
|
.labelData(pdfs.getRouterlabelZebra())
.build())
.build();
}
@Override
public @NonNull JsonDeliveryAdvisorResponse adviseShipment(final @NonNull JsonDeliveryAdvisorRequest request)
{
return JsonDeliveryAdvisorResponse.builder()
.requestId(request.getId())
.shipperProduct(JsonShipperProduct.builder()
.code(GOShipperProduct.Overnight.getCode())
.build())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GOClient.java
| 1
|
请完成以下Java代码
|
public class CurrentUserToken extends DefaultOidcUser {
@Serial
private static final long serialVersionUID = 332175240400944267L;
private final Collection<GrantedAuthority> authorities;
private final UUID userId;
private final String username;
private final String email;
public CurrentUserToken(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken, OidcUserInfo userInfo) {
super(authorities, idToken, userInfo);
this.authorities = SecurityUtils.extractAuthorityFromClaims(userInfo.getClaims());
this.userId = UUID.fromString(getName());
this.username = getAttribute("preferred_username");
this.email = getAttribute("email");
}
public CurrentUserToken(Collection<GrantedAuthority> authorities, String username) {
super(authorities, OidcIdToken.withTokenValue("DUMMY-TEST").claim("DUMMY", "DUMMY").claim("sub", username).build());
this.authorities = authorities;
this.userId = null;
this.username = username;
this.email = null;
}
@JsonIgnore
public boolean isUser() {
return getGrantedAuthorities().contains(Constants.ROLE_USER);
}
@JsonIgnore
public boolean isAdmin() {
return getGrantedAuthorities().contains(Constants.ROLE_ADMIN);
}
@JsonIgnore
public Collection<String> getGrantedAuthorities() {
Collection<GrantedAuthority> authorities = getAuthorities();
return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
}
@JsonIgnore
public Collection<GrantedAuthority> getAuthorities() {
return authorities;
}
public UserToken getUserToken() {
|
return new UserToken(getUsername(), getIdToken().getTokenValue(), getGrantedAuthorities());
}
public record UserToken(String username, String token, Collection<String> roles) {
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
CurrentUserToken that = (CurrentUserToken) o;
return Objects.equals(userId, that.userId);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), userId);
}
}
|
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\config\security\CurrentUserToken.java
| 1
|
请完成以下Java代码
|
private PurchaseRow getToplevelRowById(@NonNull final PurchaseRowId topLevelRowId)
{
final PurchaseRow topLevelRow = topLevelRowsById.get(topLevelRowId);
if (topLevelRow != null)
{
return topLevelRow;
}
throw new EntityNotFoundException("topLevelRow not found")
.appendParametersToMessage()
.setParameter("topLevelRowId", topLevelRowId);
}
public Stream<? extends IViewRow> streamTopLevelRowsByIds(@NonNull final DocumentIdsSelection rowIds)
{
if (rowIds.isAll())
{
return topLevelRowsById.values().stream();
}
return rowIds.stream().map(this::getById);
}
void patchRow(
@NonNull final PurchaseRowId idOfRowToPatch,
@NonNull final PurchaseRowChangeRequest request)
{
final PurchaseGroupRowEditor editorToUse = PurchaseRow::changeIncludedRow;
updateRow(idOfRowToPatch, request, editorToUse);
}
private void updateRow(
@NonNull final PurchaseRowId idOfRowToPatch,
@NonNull final PurchaseRowChangeRequest request,
@NonNull final PurchaseGroupRowEditor editor)
{
topLevelRowsById.compute(idOfRowToPatch.toGroupRowId(), (groupRowId, groupRow) -> {
if (groupRow == null)
{
throw new EntityNotFoundException("Row not found").appendParametersToMessage().setParameter("rowId", groupRowId);
|
}
final PurchaseRow newGroupRow = groupRow.copy();
if (idOfRowToPatch.isGroupRowId())
{
final PurchaseRowId includedRowId = null;
editor.edit(newGroupRow, includedRowId, request);
}
else
{
final PurchaseRowId includedRowId = idOfRowToPatch;
editor.edit(newGroupRow, includedRowId, request);
}
return newGroupRow;
});
}
@FunctionalInterface
private static interface PurchaseGroupRowEditor
{
void edit(final PurchaseRow editableGroupRow, final PurchaseRowId includedRowId, final PurchaseRowChangeRequest request);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowsCollection.java
| 1
|
请完成以下Java代码
|
public static void addToEnvironment(ConfigurableEnvironment environment) {
addToEnvironment(environment, logger);
}
/**
* Add a {@link RandomValuePropertySource} to the given {@link Environment}.
* @param environment the environment to add the random property source to
* @param logger logger used for debug and trace information
* @since 4.0.0
*/
public static void addToEnvironment(ConfigurableEnvironment environment, Log logger) {
MutablePropertySources sources = environment.getPropertySources();
PropertySource<?> existing = sources.get(RANDOM_PROPERTY_SOURCE_NAME);
if (existing != null) {
logger.trace("RandomValuePropertySource already present");
return;
}
RandomValuePropertySource randomSource = new RandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME);
if (sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) != null) {
sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, randomSource);
}
else {
sources.addLast(randomSource);
}
logger.trace("RandomValuePropertySource add to Environment");
}
static final class Range<T extends Number> {
private final String value;
private final T min;
private final T max;
private Range(String value, T min, T max) {
this.value = value;
this.min = min;
this.max = max;
|
}
T getMin() {
return this.min;
}
T getMax() {
return this.max;
}
@Override
public String toString() {
return this.value;
}
static <T extends Number & Comparable<T>> Range<T> of(String value, Function<String, T> parse) {
T zero = parse.apply("0");
String[] tokens = StringUtils.commaDelimitedListToStringArray(value);
T min = parse.apply(tokens[0]);
if (tokens.length == 1) {
Assert.state(min.compareTo(zero) > 0, "Bound must be positive.");
return new Range<>(value, zero, min);
}
T max = parse.apply(tokens[1]);
Assert.state(min.compareTo(max) < 0, "Lower bound must be less than upper bound.");
return new Range<>(value, min, max);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\RandomValuePropertySource.java
| 1
|
请完成以下Java代码
|
public class DefaultIdentityLinkInterceptor implements IdentityLinkInterceptor {
@Override
public void handleCompleteTask(TaskEntity task) {
if (Authentication.getAuthenticatedUserId() != null && task.getProcessInstanceId() != null) {
ExecutionEntity processInstanceEntity = CommandContextUtil.getExecutionEntityManager().findById(task.getProcessInstanceId());
IdentityLinkUtil.createProcessInstanceIdentityLink(processInstanceEntity,
Authentication.getAuthenticatedUserId(), null, IdentityLinkType.PARTICIPANT);
}
}
@Override
public void handleAddIdentityLinkToTask(TaskEntity taskEntity, IdentityLinkEntity identityLinkEntity) {
addUserIdentityLinkToParent(taskEntity, identityLinkEntity.getUserId());
}
@Override
public void handleAddAssigneeIdentityLinkToTask(TaskEntity taskEntity, String assignee) {
addUserIdentityLinkToParent(taskEntity, assignee);
}
@Override
public void handleAddOwnerIdentityLinkToTask(TaskEntity taskEntity, String owner) {
addUserIdentityLinkToParent(taskEntity, owner);
}
@Override
public void handleCreateProcessInstance(ExecutionEntity processInstanceExecution) {
String authenticatedUserId = Authentication.getAuthenticatedUserId();
if (authenticatedUserId != null) {
IdentityLinkUtil.createProcessInstanceIdentityLink(processInstanceExecution, authenticatedUserId, null, IdentityLinkType.STARTER);
}
}
@Override
public void handleCreateSubProcessInstance(ExecutionEntity subProcessInstanceExecution, ExecutionEntity superExecution) {
|
String authenticatedUserId = Authentication.getAuthenticatedUserId();
if (authenticatedUserId != null) {
IdentityLinkUtil.createProcessInstanceIdentityLink(subProcessInstanceExecution, authenticatedUserId, null, IdentityLinkType.STARTER);
}
}
protected void addUserIdentityLinkToParent(Task task, String userId) {
if (userId != null && task.getProcessInstanceId() != null) {
ExecutionEntity processInstanceEntity = CommandContextUtil.getExecutionEntityManager().findById(task.getProcessInstanceId());
for (IdentityLinkEntity identityLink : processInstanceEntity.getIdentityLinks()) {
if (identityLink.isUser() && identityLink.getUserId().equals(userId) && IdentityLinkType.PARTICIPANT.equals(identityLink.getType())) {
return;
}
}
IdentityLinkUtil.createProcessInstanceIdentityLink(processInstanceEntity, userId, null, IdentityLinkType.PARTICIPANT);
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\interceptor\DefaultIdentityLinkInterceptor.java
| 1
|
请完成以下Java代码
|
public ReactorClientHttpConnectorBuilder withCustomizers(
Collection<Consumer<ReactorClientHttpConnector>> customizers) {
return new ReactorClientHttpConnectorBuilder(mergedCustomizers(customizers), this.httpClientBuilder);
}
/**
* Return a new {@link ReactorClientHttpConnectorBuilder} that uses the given
* {@link ReactorResourceFactory} to create the underlying {@link HttpClient}.
* @param reactorResourceFactory the {@link ReactorResourceFactory} to use
* @return a new {@link ReactorClientHttpConnectorBuilder} instance
*/
public ReactorClientHttpConnectorBuilder withReactorResourceFactory(ReactorResourceFactory reactorResourceFactory) {
Assert.notNull(reactorResourceFactory, "'reactorResourceFactory' must not be null");
return new ReactorClientHttpConnectorBuilder(getCustomizers(),
this.httpClientBuilder.withReactorResourceFactory(reactorResourceFactory));
}
/**
* Return a new {@link ReactorClientHttpConnectorBuilder} that uses the given factory
* to create the underlying {@link HttpClient}.
* @param factory the factory to use
* @return a new {@link ReactorClientHttpConnectorBuilder} instance
*/
public ReactorClientHttpConnectorBuilder withHttpClientFactory(Supplier<HttpClient> factory) {
Assert.notNull(factory, "'factory' must not be null");
return new ReactorClientHttpConnectorBuilder(getCustomizers(),
this.httpClientBuilder.withHttpClientFactory(factory));
}
/**
* Return a new {@link ReactorClientHttpConnectorBuilder} that applies additional
* customization to the underlying {@link HttpClient}.
* @param httpClientCustomizer the customizer to apply
* @return a new {@link ReactorClientHttpConnectorBuilder} instance
*/
public ReactorClientHttpConnectorBuilder withHttpClientCustomizer(UnaryOperator<HttpClient> httpClientCustomizer) {
Assert.notNull(httpClientCustomizer, "'httpClientCustomizer' must not be null");
|
return new ReactorClientHttpConnectorBuilder(getCustomizers(),
this.httpClientBuilder.withHttpClientCustomizer(httpClientCustomizer));
}
/**
* Return a new {@link ReactorClientHttpConnectorBuilder} that applies the given
* customizer. This can be useful for applying pre-packaged customizations.
* @param customizer the customizer to apply
* @return a new {@link ReactorClientHttpConnectorBuilder}
* @since 4.0.0
*/
public ReactorClientHttpConnectorBuilder with(UnaryOperator<ReactorClientHttpConnectorBuilder> customizer) {
return customizer.apply(this);
}
@Override
protected ReactorClientHttpConnector createClientHttpConnector(HttpClientSettings settings) {
HttpClient httpClient = this.httpClientBuilder.build(settings);
return new ReactorClientHttpConnector(httpClient);
}
static class Classes {
static final String HTTP_CLIENT = "reactor.netty.http.client.HttpClient";
static boolean present(@Nullable ClassLoader classLoader) {
return ClassUtils.isPresent(HTTP_CLIENT, classLoader);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\reactive\ReactorClientHttpConnectorBuilder.java
| 1
|
请完成以下Java代码
|
public B type(String type) {
return header(JoseHeaderNames.TYP, type);
}
/**
* Sets the content type header that declares the media type of the secured
* content (the payload).
* @param contentType the content type header
* @return the {@link AbstractBuilder}
*/
public B contentType(String contentType) {
return header(JoseHeaderNames.CTY, contentType);
}
/**
* Sets the critical header that indicates which extensions to the JWS/JWE/JWA
* specifications are being used that MUST be understood and processed.
* @param name the critical header name
* @param value the critical header value
* @return the {@link AbstractBuilder}
*/
@SuppressWarnings("unchecked")
public B criticalHeader(String name, Object value) {
header(name, value);
getHeaders().computeIfAbsent(JoseHeaderNames.CRIT, (k) -> new HashSet<String>());
((Set<String>) getHeaders().get(JoseHeaderNames.CRIT)).add(name);
return getThis();
}
/**
* Sets the header.
* @param name the header name
* @param value the header value
* @return the {@link AbstractBuilder}
*/
public B header(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.headers.put(name, value);
return getThis();
}
|
/**
* A {@code Consumer} to be provided access to the headers allowing the ability to
* add, replace, or remove.
* @param headersConsumer a {@code Consumer} of the headers
* @return the {@link AbstractBuilder}
*/
public B headers(Consumer<Map<String, Object>> headersConsumer) {
headersConsumer.accept(this.headers);
return getThis();
}
/**
* Builds a new {@link JoseHeader}.
* @return a {@link JoseHeader}
*/
public abstract T build();
private static URL convertAsURL(String header, String value) {
URL convertedValue = ClaimConversionService.getSharedInstance().convert(value, URL.class);
Assert.notNull(convertedValue,
() -> "Unable to convert header '" + header + "' of type '" + value.getClass() + "' to URL.");
return convertedValue;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JoseHeader.java
| 1
|
请完成以下Java代码
|
public String getResource() {
return rule.getResource();
}
@JsonIgnore
@JSONField(serialize = false)
public int getGrade() {
return rule.getGrade();
}
@JsonIgnore
@JSONField(serialize = false)
public Integer getParamIdx() {
return rule.getParamIdx();
}
@JsonIgnore
@JSONField(serialize = false)
public double getCount() {
return rule.getCount();
}
@JsonIgnore
@JSONField(serialize = false)
public List<ParamFlowItem> getParamFlowItemList() {
return rule.getParamFlowItemList();
}
@JsonIgnore
@JSONField(serialize = false)
public int getControlBehavior() {
return rule.getControlBehavior();
}
@JsonIgnore
@JSONField(serialize = false)
public int getMaxQueueingTimeMs() {
return rule.getMaxQueueingTimeMs();
}
@JsonIgnore
|
@JSONField(serialize = false)
public int getBurstCount() {
return rule.getBurstCount();
}
@JsonIgnore
@JSONField(serialize = false)
public long getDurationInSec() {
return rule.getDurationInSec();
}
@JsonIgnore
@JSONField(serialize = false)
public boolean isClusterMode() {
return rule.isClusterMode();
}
@JsonIgnore
@JSONField(serialize = false)
public ParamFlowClusterConfig getClusterConfig() {
return rule.getClusterConfig();
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\ParamFlowRuleEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MyChannelInterceptor implements ChannelInterceptor {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
System.out.println("----------------------------preSend------------------------------");
return message;
}
@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
}
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
|
}
@Override
public boolean preReceive(MessageChannel channel) {
return true;
}
@Override
public Message<?> postReceive(Message<?> message, MessageChannel channel) {
System.out.println("----------------------------postReceive------------------------------");
return message;
}
@Override
public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
}
}
|
repos\springboot-demo-master\sftp\src\main\java\com\et\sftp\Interceptor\MyChannelInterceptor.java
| 2
|
请完成以下Java代码
|
public void setAdditionalInfoField(String field, JsonNode value) {
JsonNode additionalInfo = getAdditionalInfo();
if (!(additionalInfo instanceof ObjectNode)) {
additionalInfo = mapper.createObjectNode();
}
((ObjectNode) additionalInfo).set(field, value);
setAdditionalInfo(additionalInfo);
}
public <T> T getAdditionalInfoField(String field, Function<JsonNode, T> mapper, T defaultValue) {
JsonNode additionalInfo = getAdditionalInfo();
if (additionalInfo != null && additionalInfo.has(field)) {
return mapper.apply(additionalInfo.get(field));
}
return defaultValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
BaseDataWithAdditionalInfo<?> that = (BaseDataWithAdditionalInfo<?>) o;
return Arrays.equals(additionalInfoBytes, that.additionalInfoBytes);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), additionalInfoBytes);
}
public static JsonNode getJson(Supplier<JsonNode> jsonData, Supplier<byte[]> binaryData) {
JsonNode json = jsonData.get();
if (json != null) {
return json;
} else {
byte[] data = binaryData.get();
if (data != null) {
try {
|
return mapper.readTree(new ByteArrayInputStream(data));
} catch (IOException e) {
log.warn("Can't deserialize json data: ", e);
return null;
}
} else {
return null;
}
}
}
public static void setJson(JsonNode json, Consumer<JsonNode> jsonConsumer, Consumer<byte[]> bytesConsumer) {
jsonConsumer.accept(json);
try {
bytesConsumer.accept(mapper.writeValueAsBytes(json));
} catch (JsonProcessingException e) {
log.warn("Can't serialize json data: ", e);
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\BaseDataWithAdditionalInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Config {
@Bean(initMethod = "init", destroyMethod = "close")
public AtomikosDataSourceBean inventoryDataSource() {
AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean();
dataSource.setLocalTransactionMode(true);
dataSource.setUniqueResourceName("db1");
dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource");
Properties xaProperties = new Properties();
xaProperties.put("databaseName", "db1");
xaProperties.put("createDatabase", "create");
dataSource.setXaProperties(xaProperties);
dataSource.setPoolSize(10);
return dataSource;
}
@Bean(initMethod = "init", destroyMethod = "close")
public AtomikosDataSourceBean orderDataSource() {
AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean();
dataSource.setLocalTransactionMode(true);
dataSource.setUniqueResourceName("db2");
dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource");
Properties xaProperties = new Properties();
xaProperties.put("databaseName", "db2");
xaProperties.put("createDatabase", "create");
dataSource.setXaProperties(xaProperties);
dataSource.setPoolSize(10);
return dataSource;
}
@Bean(initMethod = "init", destroyMethod = "close")
public UserTransactionManager userTransactionManager() throws jakarta.transaction.SystemException {
UserTransactionManager userTransactionManager = new UserTransactionManager();
userTransactionManager.setTransactionTimeout(300);
userTransactionManager.setForceShutdown(true);
|
return userTransactionManager;
}
@Bean
public JtaTransactionManager jtaTransactionManager() throws SystemException {
JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
jtaTransactionManager.setTransactionManager(userTransactionManager());
jtaTransactionManager.setUserTransaction(userTransactionManager());
return jtaTransactionManager;
}
@Bean
public Application application() {
return new Application(inventoryDataSource(), orderDataSource());
}
}
|
repos\tutorials-master\persistence-modules\atomikos\src\main\java\com\baeldung\atomikos\spring\config\Config.java
| 2
|
请完成以下Java代码
|
public class VariableListenerInvocationListener implements VariableInstanceLifecycleListener<VariableInstanceEntity> {
protected final AbstractVariableScope targetScope;
public VariableListenerInvocationListener(AbstractVariableScope targetScope) {
this.targetScope = targetScope;
}
@Override
public void onCreate(VariableInstanceEntity variable, AbstractVariableScope sourceScope) {
handleEvent(new VariableEvent(variable, VariableListener.CREATE, sourceScope));
}
@Override
public void onUpdate(VariableInstanceEntity variable, AbstractVariableScope sourceScope) {
handleEvent(new VariableEvent(variable, VariableListener.UPDATE, sourceScope));
}
@Override
public void onDelete(VariableInstanceEntity variable, AbstractVariableScope sourceScope) {
handleEvent(new VariableEvent(variable, VariableListener.DELETE, sourceScope));
}
protected void handleEvent(VariableEvent event) {
AbstractVariableScope sourceScope = event.getSourceScope();
if (sourceScope instanceof ExecutionEntity) {
addEventToScopeExecution((ExecutionEntity) sourceScope, event);
} else if (sourceScope instanceof TaskEntity) {
TaskEntity task = (TaskEntity) sourceScope;
ExecutionEntity execution = task.getExecution();
if (execution != null) {
addEventToScopeExecution(execution, event);
}
|
} else if(sourceScope.getParentVariableScope() instanceof ExecutionEntity) {
addEventToScopeExecution((ExecutionEntity)sourceScope.getParentVariableScope(), event);
}
else {
throw new ProcessEngineException("BPMN execution scope expected");
}
}
protected void addEventToScopeExecution(ExecutionEntity sourceScope, VariableEvent event) {
// ignore events of variables that are not set in an execution
ExecutionEntity sourceExecution = sourceScope;
ExecutionEntity scopeExecution = sourceExecution.isScope() ? sourceExecution : sourceExecution.getParent();
scopeExecution.delayEvent((ExecutionEntity) targetScope, event);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableListenerInvocationListener.java
| 1
|
请完成以下Java代码
|
private static ITranslatableString toTrl(@Nullable final String reasonStr)
{
if (reasonStr == null || Check.isBlank(reasonStr))
{
return TranslatableStrings.empty();
}
else
{
return TranslatableStrings.anyLanguage(reasonStr.trim());
}
}
public static final BooleanWithReason TRUE = new BooleanWithReason(true, TranslatableStrings.empty());
public static final BooleanWithReason FALSE = new BooleanWithReason(false, TranslatableStrings.empty());
private final boolean value;
@NonNull @Getter private final ITranslatableString reason;
private BooleanWithReason(
final boolean value,
@NonNull final ITranslatableString reason)
{
this.value = value;
this.reason = reason;
}
@Override
public String toString()
{
final String valueStr = String.valueOf(value);
final String reasonStr = !TranslatableStrings.isBlank(reason)
? reason.getDefaultValue()
: null;
return reasonStr != null
? valueStr + " because " + reasonStr
: valueStr;
}
public boolean toBoolean()
{
return value;
}
|
public boolean isTrue()
{
return value;
}
public boolean isFalse()
{
return !value;
}
public String getReasonAsString()
{
return reason.getDefaultValue();
}
public void assertTrue()
{
if (isFalse())
{
throw new AdempiereException(reason);
}
}
public BooleanWithReason and(@NonNull final Supplier<BooleanWithReason> otherSupplier)
{
return isFalse()
? this
: Check.assumeNotNull(otherSupplier.get(), "otherSupplier shall not return null");
}
public void ifTrue(@NonNull final Consumer<String> consumer)
{
if (isTrue())
{
consumer.accept(getReasonAsString());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\BooleanWithReason.java
| 1
|
请完成以下Java代码
|
public CardAggregated1 getAggtd() {
return aggtd;
}
/**
* Sets the value of the aggtd property.
*
* @param value
* allowed object is
* {@link CardAggregated1 }
*
*/
public void setAggtd(CardAggregated1 value) {
this.aggtd = value;
}
/**
* Gets the value of the indv property.
*
* @return
* possible object is
* {@link CardIndividualTransaction1 }
*
*/
|
public CardIndividualTransaction1 getIndv() {
return indv;
}
/**
* Sets the value of the indv property.
*
* @param value
* allowed object is
* {@link CardIndividualTransaction1 }
*
*/
public void setIndv(CardIndividualTransaction1 value) {
this.indv = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardTransaction1Choice.java
| 1
|
请完成以下Java代码
|
protected String getDeploymentMode() {
return DEPLOYMENT_MODE;
}
@Override
public void deployResources(String deploymentNameHint, Resource[] resources, RepositoryService repositoryService) {
DeploymentBuilder deploymentBuilder = repositoryService
.createDeployment()
.enableDuplicateFiltering()
.name(deploymentNameHint);
int validProcessCount = 0;
for (final Resource resource : resources) {
final String resourceName = determineResourceName(resource);
if (validateModel(resource, repositoryService)) {
validProcessCount++;
deploymentBuilder.addInputStream(resourceName, resource);
} else {
|
LOGGER.error(
"The following resource wasn't included in the deployment since it is invalid:\n{}",
resourceName
);
}
}
deploymentBuilder = loadApplicationUpgradeContext(deploymentBuilder);
if (validProcessCount != 0) {
deploymentBuilder.deploy();
} else {
throw new ActivitiException("No process definition was deployed.");
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\autodeployment\FailOnNoProcessAutoDeploymentStrategy.java
| 1
|
请完成以下Java代码
|
public static boolean removeDelegateAppender(ch.qos.logback.classic.Logger logger) {
return removeAppender(logger, DELEGATE_APPENDER_NAME);
}
/**
* Converts an SLF4J {@link Logger} to a Logback {@link ch.qos.logback.classic.Logger}.
*
* @param logger SLF4J {@link Logger} to convert.
* @return an {@link Optional} Logback {@link ch.qos.logback.classic.Logger} for the given SLF4J {@link Logger}
* iff the SLF4J {@link Logger} is {@literal not-null} and is a Logback {@link ch.qos.logback.classic.Logger}.
* @see java.util.Optional
* @see ch.qos.logback.classic.Logger
* @see org.slf4j.Logger
*/
public static Optional<ch.qos.logback.classic.Logger> toLogbackLogger(Logger logger) {
return slf4jLoggerToLogbackLoggerConverter.apply(logger);
}
private static String nullSafeLoggerName(Logger logger) {
return logger != null ? logger.getName() : null;
}
private static Class<?> nullSafeType(Object obj) {
return obj != null ? obj.getClass() : null;
}
|
private static String nullSafeTypeName(Class<?> type) {
return type != null ? type.getName() : null;
}
private static String nullSafeTypeName(Object obj) {
return nullSafeTypeName(nullSafeType(obj));
}
private static String nullSafeTypeSimpleName(Class<?> type) {
return type != null ? type.getSimpleName() : null;
}
private static String nullSafeTypeSimpleName(Object obj) {
return nullSafeTypeSimpleName(nullSafeType(obj));
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\support\LogbackSupport.java
| 1
|
请完成以下Java代码
|
public void setC_BPartner_Alberta_ID (final int C_BPartner_Alberta_ID)
{
if (C_BPartner_Alberta_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Alberta_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Alberta_ID, C_BPartner_Alberta_ID);
}
@Override
public int getC_BPartner_Alberta_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Alberta_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setIsArchived (final boolean IsArchived)
{
set_Value (COLUMNNAME_IsArchived, IsArchived);
}
@Override
public boolean isArchived()
{
|
return get_ValueAsBoolean(COLUMNNAME_IsArchived);
}
@Override
public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp)
{
set_Value (COLUMNNAME_Timestamp, Timestamp);
}
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
@Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
@Override
public void setTitleShort (final @Nullable java.lang.String TitleShort)
{
set_Value (COLUMNNAME_TitleShort, TitleShort);
}
@Override
public java.lang.String getTitleShort()
{
return get_ValueAsString(COLUMNNAME_TitleShort);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_Alberta.java
| 1
|
请完成以下Java代码
|
public final class TableColumnResource implements Resource
{
/** Any table column */
public static final TableColumnResource ANY = new TableColumnResource();
public static final TableColumnResource of(final int adTableId, final int adColumnId)
{
return new TableColumnResource(adTableId, adColumnId);
}
private final int AD_Table_ID;
private final int AD_Column_ID;
private int hashcode = 0;
private TableColumnResource(final int AD_Table_ID, final int AD_Column_ID)
{
super();
Check.assume(AD_Table_ID > 0, "AD_Table_ID > 0");
this.AD_Table_ID = AD_Table_ID;
Check.assume(AD_Column_ID > 0, "AD_Column_ID > 0");
this.AD_Column_ID = AD_Column_ID;
}
/** Any table column constructor */
private TableColumnResource()
{
super();
this.AD_Table_ID = -1;
this.AD_Column_ID = -1;
}
@Override
public String toString()
{
return "@AD_Column_ID@="
+ (this == ANY ? "*" : AD_Table_ID + "/" + AD_Column_ID);
}
@Override
public int hashCode()
{
if (hashcode == 0)
{
hashcode = new HashcodeBuilder()
.append(31) // seed
.append(AD_Table_ID)
.append(AD_Column_ID)
.toHashcode();
}
return hashcode;
}
@Override
public boolean equals(final Object obj)
|
{
if (this == obj)
{
return true;
}
final TableColumnResource other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(AD_Table_ID, other.AD_Table_ID)
.append(AD_Column_ID, other.AD_Column_ID)
.isEqual();
}
public int getAD_Table_ID()
{
return AD_Table_ID;
}
public int getAD_Column_ID()
{
return AD_Column_ID;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnResource.java
| 1
|
请完成以下Java代码
|
public String decrypt(String value) {
if (StringUtils.isEmpty(value)) {
return "";
}
try {
byte[] encryptData = Hex.hexStringToBytes(value);
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] content = cipher.doFinal(encryptData);
return new String(content, "UTF-8");
} catch (Exception e) {
log.error("AES解密时出现问题,密钥为:{},密文为:{}", password, value);
throw new IllegalStateException("AES解密时出现问题" + e.getMessage(), e);
}
}
|
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//AES 要求密钥长度为 128
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
kg.init(128, random);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
// 转换为AES专用密钥
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}
}
|
repos\spring-boot-quick-master\mybatis-crypt-plugin\src\main\java\com\quick\db\crypt\encrypt\AesDesDefaultEncrypt.java
| 1
|
请完成以下Java代码
|
public class AD_Role_RevokePermission extends JavaProcess
{
private int p_AD_Role_PermRequest_ID = -1;
@Override
protected void prepare()
{
if (getTable_ID() == MRolePermRequest.Table_ID)
{
p_AD_Role_PermRequest_ID = getRecord_ID();
}
}
@Override
protected String doIt() throws Exception
{
if (p_AD_Role_PermRequest_ID <= 0)
throw new FillMandatoryException(MRolePermRequest.COLUMNNAME_AD_Role_PermRequest_ID);
|
//
final MRolePermRequest req = new MRolePermRequest(getCtx(), p_AD_Role_PermRequest_ID, get_TrxName());
RolePermRevokeAccess.revokeAccess(req);
req.saveEx();
//
return "Ok";
}
@Override
protected void postProcess(boolean success)
{
if (success)
{
Services.get(IUserRolePermissionsDAO.class).resetCacheAfterTrxCommit();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\process\AD_Role_RevokePermission.java
| 1
|
请完成以下Java代码
|
public void onAttributeValueChanged(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue, final Object valueOld)
{
for (final IAttributeStorageListener listener : listeners)
{
listener.onAttributeValueChanged(attributeValueContext, storage, attributeValue, valueOld);
}
}
@Override
public void onAttributeValueDeleted(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue)
{
for (final IAttributeStorageListener listener : listeners)
{
listener.onAttributeValueDeleted(attributeValueContext, storage, attributeValue);
}
}
@Override
public void onAttributeStorageDisposed(final IAttributeStorage storage)
{
// if a listener gets notified about this event, it might well remove itself from this composite.
// In order to prevent a ConcurrentModificationException, we iterate a copy
|
final ArrayList<IAttributeStorageListener> listenersToIterate = new ArrayList<>(listeners);
for (final IAttributeStorageListener listener : listenersToIterate)
{
listener.onAttributeStorageDisposed(storage);
}
}
@Override
public String toString()
{
return "CompositeAttributeStorageListener [listeners=" + listeners + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CompositeAttributeStorageListener.java
| 1
|
请完成以下Java代码
|
public static <T> CommonPage<T> restPage(Page<T> pageInfo) {
CommonPage<T> result = new CommonPage<T>();
result.setTotalPage(pageInfo.getTotalPages());
result.setPageNum(pageInfo.getNumber());
result.setPageSize(pageInfo.getSize());
result.setTotal(pageInfo.getTotalElements());
result.setList(pageInfo.getContent());
return result;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
|
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
}
|
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\api\CommonPage.java
| 1
|
请完成以下Java代码
|
private String convert (long number)
{
/* special case */
if (number == 0)
{
return "Kosong";
}
String prefix = "";
if (number < 0)
{
number = -number;
prefix = "Negatif ";
}
String soFar = "";
int place = 0;
do
{
long n = number % 1000;
if (n != 0)
{
String s = convertLessThanOneThousand ((int)n);
soFar = s + majorNames[place] + soFar;
}
place++;
number /= 1000;
}
while (number > 0);
return (prefix + soFar).trim ();
} // convert
/**************************************************************************
* Get Amount in Words
* @param amount numeric amount (352.80)
* @return amount in words (three*five*two 80/100)
* @throws Exception
*/
public String getAmtInWords (String amount) throws Exception
{
if (amount == null)
return amount;
//
StringBuffer sb = new StringBuffer ();
sb.append("RINGGIT ");
int pos = amount.lastIndexOf ('.');
int pos2 = amount.lastIndexOf (',');
if (pos2 > pos)
pos = pos2;
String oldamt = amount;
amount = amount.replaceAll (",", "");
int newpos = amount.lastIndexOf ('.');
|
long dollars = Long.parseLong(amount.substring (0, newpos));
sb.append (convert (dollars));
for (int i = 0; i < oldamt.length (); i++)
{
if (pos == i) // we are done
{
String cents = oldamt.substring (i + 1);
long sen = Long.parseLong(cents); //red1 convert cents to words
sb.append(" dan SEN");
sb.append (' ').append (convert(sen));
break;
}
}
return sb.toString ();
} // getAmtInWords
/**
* Test Print
* @param amt amount
*/
private void print (String amt)
{
try
{
System.out.println(amt + " = " + getAmtInWords(amt));
}
catch (Exception e)
{
e.printStackTrace();
}
} // print
/**
* Test
* @param args ignored
*/
public static void main (String[] args)
{
AmtInWords_MS aiw = new AmtInWords_MS();
// aiw.print (".23"); Error
aiw.print ("0.23");
aiw.print ("1.23");
aiw.print ("12.34");
aiw.print ("123.45");
aiw.print ("1,234.56");
aiw.print ("12,345.78");
aiw.print ("123,457.89");
aiw.print ("1,234,578.90");
aiw.print ("100.00");
} // main
} // AmtInWords_MY
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_MS.java
| 1
|
请完成以下Java代码
|
private Map<String, String> prepareParameterList(final @NonNull GeoCoordinatesRequest request)
{
final String defaultEmptyValue = "";
final Map<String, String> m = new HashMap<>();
m.put("numberAndStreet", CoalesceUtil.coalesce(request.getAddress(), defaultEmptyValue));
m.put("postalcode", CoalesceUtil.coalesce(request.getPostal(), defaultEmptyValue));
m.put("city", CoalesceUtil.coalesce(request.getCity(), defaultEmptyValue));
m.put("countrycodes", request.getCountryCode2());
m.put("format", "json");
m.put("dedupe", "1");
m.put("email", "openstreetmapbot@metasfresh.com");
m.put("polygon_geojson", "0");
m.put("polygon_kml", "0");
m.put("polygon_svg", "0");
m.put("polygon_text", "0");
return m;
}
private static GeographicalCoordinates toGeographicalCoordinates(final NominatimOSMGeographicalCoordinatesJSON json)
{
return GeographicalCoordinates.builder()
.latitude(new BigDecimal(json.getLat()))
.longitude(new BigDecimal(json.getLon()))
|
.build();
}
private void sleepMillis(final long timeToSleep)
{
if (timeToSleep <= 0)
{
return;
}
try
{
logger.trace("Sleeping {}ms (rate limit)", timeToSleep);
TimeUnit.MILLISECONDS.sleep(timeToSleep);
}
catch (final InterruptedException e)
{
// nothing to do here
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\provider\openstreetmap\NominatimOSMGeocodingProviderImpl.java
| 1
|
请完成以下Java代码
|
public void processRow(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
String name = resultSet.getString("Name");
// process it
}
}
});
}
void startBookBatchUpdateRollBack(int size) {
jdbcTemplate.execute("CREATE TABLE books(" +
"id SERIAL, name VARCHAR(255), price NUMERIC(15, 2))");
List<Book> books = new ArrayList();
for (int count = 0; count < size; count++) {
if (count == 500) {
// create a invalid data for id 500, test rollback
// name allow 255, this book has length of 300
books.add(new Book(NameGenerator.randomName(300), new BigDecimal(1.99)));
continue;
}
books.add(new Book(NameGenerator.randomName(20), new BigDecimal(1.99)));
}
try {
// with @Transactional, any error, entire batch will be roll back
bookRepository.batchInsert(books, 100);
} catch (Exception e) {
System.err.println(e.getMessage());
}
List<Book> bookFromDatabase = bookRepository.findAll();
// count = 0 , id 500 error, roll back all
log.info("Total books: {}", bookFromDatabase.size());
}
void startBookBatchUpdateApp(int size) {
//jdbcTemplate.execute("DROP TABLE books IF EXISTS");
jdbcTemplate.execute("CREATE TABLE books(" +
"id SERIAL, name VARCHAR(255), price NUMERIC(15, 2))");
List<Book> books = new ArrayList();
for (int count = 0; count < size; count++) {
books.add(new Book(NameGenerator.randomName(20), new BigDecimal(1.99)));
}
|
// batch insert
bookRepository.batchInsert(books);
List<Book> bookFromDatabase = bookRepository.findAll();
// count
log.info("Total books: {}", bookFromDatabase.size());
// random
log.info("{}", bookRepository.findById(2L).orElseThrow(IllegalArgumentException::new));
log.info("{}", bookRepository.findById(500L).orElseThrow(IllegalArgumentException::new));
// update all books to 9.99
bookFromDatabase.forEach(x -> x.setPrice(new BigDecimal(9.99)));
// batch update
bookRepository.batchUpdate(bookFromDatabase);
List<Book> updatedList = bookRepository.findAll();
// count
log.info("Total books: {}", updatedList.size());
// random
log.info("{}", bookRepository.findById(2L).orElseThrow(IllegalArgumentException::new));
log.info("{}", bookRepository.findById(500L).orElseThrow(IllegalArgumentException::new));
}
}
|
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\StartApplication.java
| 1
|
请完成以下Java代码
|
public class FileSearchCost {
private final static String FILE_NAME = "src/main/resources/Test";
@Setup(Level.Trial)
public void setup() throws IOException {
for (int i = 0; i < 1500; i++) {
File targetFile = new File(FILE_NAME + i);
FileUtils.writeStringToFile(targetFile, "Test", "UTF8");
}
}
@TearDown(Level.Trial)
public void tearDown() {
for (int i = 0; i < 1500; i++) {
File fileToDelete = new File(FILE_NAME + i);
fileToDelete.delete();
}
}
|
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void textFileSearchSequential() throws IOException {
Files.walk(Paths.get("src/main/resources/")).map(Path::normalize).filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt")).collect(Collectors.toList());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void textFileSearchParallel() throws IOException {
Files.walk(Paths.get("src/main/resources/")).parallel().map(Path::normalize).filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt")).collect(Collectors.toList());
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\parallel\FileSearchCost.java
| 1
|
请完成以下Java代码
|
public class Book {
private Long id;
private String name;
private String author;
private Date date;
@XmlAttribute
public void setId(Long id) {
this.id = id;
}
@XmlElement(name = "title")
public void setName(String name) {
this.name = name;
}
@XmlTransient
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
|
this.date = date;
}
public Long getId() {
return id;
}
public String getAuthor() {
return author;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\Book.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.