instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public String home() { return format("HTTP Session Caching Example"); } @GetMapping("/ping") @ResponseBody public String ping() { return format("PONG"); } @GetMapping("/session") public ModelAndView sessionRequestCounts(HttpSession session) { this.sessionIds.add(session.getId()); Map<String, Object> model = new HashMap<>(); model.put("sessionType", session.getClass().getName()); model.put("sessionCount", this.sessionIds.size()); model.put("requestCount", getRequestCount(session)); return new ModelAndView(INDEX_TEMPLATE_VIEW_NAME, model); } private Object getRequestCount(HttpSession session) {
Integer requestCount = (Integer) session.getAttribute("requestCount"); requestCount = requestCount != null ? requestCount : 0; requestCount++; session.setAttribute("requestCount", requestCount); return requestCount; } private String format(String value) { return String.format("<h1>%s</h1>", value); } } //end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\http-session\src\main\java\example\app\caching\session\http\controller\CounterController.java
2
请完成以下Java代码
public HUAttributeQueryFilterVO addValues(final Collection<? extends Object> values) { setMatchingType(AttributeValueMatchingType.ValuesList); final boolean added = _values.addAll(values); if (added) { _valuesAndSubstitutes = null; } return this; } private AttributeId getAttributeId() { return attributeId; } /** * @return attribute; never return <code>null</code> */ private I_M_Attribute getM_Attribute() { return attribute; } public HUAttributeQueryFilterVO assertAttributeValueType(@NonNull final String attributeValueType) { Check.assume( Objects.equals(this.attributeValueType, attributeValueType), "Invalid attributeValueType for {}. Expected: {}", this, attributeValueType); return this; } private ModelColumn<I_M_HU_Attribute, Object> getHUAttributeValueColumn() { return huAttributeValueColumn; } private Set<Object> getValues() { return _values; } private Set<Object> getValuesAndSubstitutes()
{ if (_valuesAndSubstitutes != null) { return _valuesAndSubstitutes; } final ModelColumn<I_M_HU_Attribute, Object> valueColumn = getHUAttributeValueColumn(); final boolean isStringValueColumn = I_M_HU_Attribute.COLUMNNAME_Value.equals(valueColumn.getColumnName()); final Set<Object> valuesAndSubstitutes = new HashSet<>(); // // Iterate current values for (final Object value : getValues()) { // Append current value to result valuesAndSubstitutes.add(value); // Search and append it's substitutes too, if found if (isStringValueColumn && value instanceof String) { final String valueStr = value.toString(); final I_M_Attribute attribute = getM_Attribute(); final Set<String> valueSubstitutes = attributeDAO.retrieveAttributeValueSubstitutes(attribute, valueStr); valuesAndSubstitutes.addAll(valueSubstitutes); } } _valuesAndSubstitutes = valuesAndSubstitutes; return _valuesAndSubstitutes; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAttributeQueryFilterVO.java
1
请在Spring Boot框架中完成以下Java代码
public ImmutableSet<HuId> filterSplitHUsForSharingQr(@NonNull final I_M_HU sourceHU, @NonNull final ImmutableList<I_M_HU> newHUs) { if (!isOneQrCodeForAggregatedHUsEnabledFor(sourceHU)) { return ImmutableSet.of(); } return newHUs.stream() .flatMap(newHU -> { if (handlingUnitsBL.isLoadingUnit(newHU)) { return handlingUnitsDAO.retrieveIncludedHUs(newHU).stream(); } else { return Stream.of(newHU); } }) .filter(handlingUnitsBL::isTransportUnitOrAggregate) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); }
public boolean isAtLeastOneActiveConfig() { return repository.isAtLeastOneActiveConfig(); } @NonNull public ImmutableMap<QRCodeConfigurationId, QRCodeConfiguration> getByIds(@NonNull final ImmutableSet<QRCodeConfigurationId> qrCodeConfigurationIds) { return repository.getActiveByIds(qrCodeConfigurationIds); } @NonNull private Optional<QRCodeConfiguration> getConfigurationForHuId(@NonNull final I_M_HU hu) { final ProductId productId = handlingUnitsBL.getStorageFactory().getStorage(hu).getSingleProductIdOrNull(); return Optional.ofNullable(productId) .map(productBL::getById) .map(I_M_Product::getQRCode_Configuration_ID) .map(QRCodeConfigurationId::ofRepoIdOrNull) .flatMap(repository::getActiveById); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\QRCodeConfigurationService.java
2
请完成以下Java代码
private static String buildRequestUrl(String servletPath, String requestURI, String contextPath, String pathInfo, String queryString) { StringBuilder url = new StringBuilder(); if (servletPath != null) { url.append(servletPath); if (pathInfo != null) { url.append(pathInfo); } } else { url.append(requestURI.substring(contextPath.length())); } if (queryString != null) { url.append("?").append(queryString); } return url.toString(); }
/** * Returns true if the supplied URL starts with a "/" or is absolute. */ public static boolean isValidRedirectUrl(String url) { return url != null && (url.startsWith("/") || isAbsoluteUrl(url)); } /** * Decides if a URL is absolute based on whether it contains a valid scheme name, as * defined in RFC 1738. */ public static boolean isAbsoluteUrl(String url) { return (url != null) ? ABSOLUTE_URL.matcher(url).matches() : false; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\UrlUtils.java
1
请完成以下Spring Boot application配置
server: port: 8000 http2: # 启用 HTTP/2 支持,提升传输效率 enabled: true compression: # 启用 GZIP 压缩,减少传输数据量 enabled: true # 需要压缩的 MIME 类型 mime-types: text/html, text/xml, text/plain, application/json # 最小压缩响应大小(字节) spring: freemarker: check-template-location: false profiles: # 激活的环境,如果需要 quartz 分布式支持,需要修改 active: dev,quartz active: dev data: redis: repositories: enabled: false # pid: # file: /自行指定位置/eladmin.pid #配置 Jpa jpa: hibernate: ddl-auto: none open-in-view: true properties: hibernate: dialect: org.hibernate.dialect.MySQL5InnoDBDialect redis: #数据库索引 database: ${REDIS_DB:0} host: ${REDIS_HOST:127.0.0.1} port: ${REDIS_PORT:6379} password: ${REDIS_PWD:} #连接超时时间 timeout: 5000 # 连接池配置 lettuce: pool: # 连接池最大连接数 max-active: 30 # 连接池最大阻塞等待时间(毫秒),负值表示没有限制 max-wait: -1 # 连接池中的最大空闲连接数 max-idle: 20 # 连接池中的最小空闲连接数 min-idle: 1 task: pool: # 核心线程池大小 core-pool-size: 10 # 最大线程数 max-pool-size: 30 # 活跃时间 keep-alive-seconds: 60 # 队列容量 queue-capacity: 50 #邮箱验证码有效时间/秒 code:
expiration: 300 #密码加密传输,前端公钥加密,后端私钥解密 rsa: private_key: MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEA0vfvyTdGJkdbHkB8mp0f3FE0GYP3AYPaJF7jUd1M0XxFSE2ceK3k2kw20YvQ09NJKk+OMjWQl9WitG9pB6tSCQIDAQABAkA2SimBrWC2/wvauBuYqjCFwLvYiRYqZKThUS3MZlebXJiLB+Ue/gUifAAKIg1avttUZsHBHrop4qfJCwAI0+YRAiEA+W3NK/RaXtnRqmoUUkb59zsZUBLpvZgQPfj1MhyHDz0CIQDYhsAhPJ3mgS64NbUZmGWuuNKp5coY2GIj/zYDMJp6vQIgUueLFXv/eZ1ekgz2Oi67MNCk5jeTF2BurZqNLR3MSmUCIFT3Q6uHMtsB9Eha4u7hS31tj1UWE+D+ADzp59MGnoftAiBeHT7gDMuqeJHPL4b+kC+gzV4FGTfhR9q3tTbklZkD2A==
repos\eladmin-master\eladmin-system\src\main\resources\config\application.yml
2
请完成以下Java代码
public CaseServiceTask clone() { CaseServiceTask clone = new CaseServiceTask(); clone.setValues(this); return clone; } public void setValues(CaseServiceTask otherElement) { super.setValues(otherElement); setCaseDefinitionKey(otherElement.getCaseDefinitionKey()); setCaseInstanceName(otherElement.getCaseInstanceName()); setBusinessKey(otherElement.getBusinessKey()); setInheritBusinessKey(otherElement.isInheritBusinessKey()); setSameDeployment(otherElement.isSameDeployment()); setFallbackToDefaultTenant(otherElement.isFallbackToDefaultTenant()); setCaseInstanceIdVariableName(otherElement.getCaseInstanceIdVariableName());
inParameters = new ArrayList<>(); if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } outParameters = new ArrayList<>(); if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) { for (IOParameter parameter : otherElement.getOutParameters()) { outParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CaseServiceTask.java
1
请完成以下Java代码
public class BankStatementLineRow implements IViewRow { @ViewColumn(seqNo = 10, widgetType = DocumentFieldWidgetType.Integer, widgetSize = WidgetSize.Small, captionKey = "Line") private final int lineNo; @ViewColumn(seqNo = 20, widgetType = DocumentFieldWidgetType.LocalDate, widgetSize = WidgetSize.Small, captionKey = "DateAcct") private final LocalDate dateAcct; @ViewColumn(seqNo = 30, widgetType = DocumentFieldWidgetType.Amount, widgetSize = WidgetSize.Small, captionKey = "StmtAmt") @Getter private final Amount statementLineAmt; @ViewColumn(seqNo = 40, widgetType = DocumentFieldWidgetType.Text, widgetSize = WidgetSize.Small, captionKey = "C_Currency_ID") private final String currencyCode; @ViewColumn(seqNo = 50, widgetType = DocumentFieldWidgetType.Text, widgetSize = WidgetSize.Large, captionKey = "Description") private final String description; // @Getter private final BankStatementLineId bankStatementLineId; private final DocumentId rowId; @Getter private final boolean reconciled; private final ViewRowFieldNameAndJsonValuesHolder<BankStatementLineRow> values; @Builder private BankStatementLineRow( @NonNull final BankStatementLineId bankStatementLineId, final int lineNo, @NonNull final LocalDate dateAcct, @NonNull final Amount statementLineAmt, @Nullable final String description, final boolean reconciled) { this.lineNo = lineNo; this.dateAcct = dateAcct; this.statementLineAmt = statementLineAmt; this.currencyCode = statementLineAmt.getCurrencyCode().toThreeLetterCode(); this.description = StringUtils.trimBlankToNull(description); this.bankStatementLineId = bankStatementLineId; this.rowId = convertBankStatementLineIdToDocumentId(bankStatementLineId); this.reconciled = reconciled; values = ViewRowFieldNameAndJsonValuesHolder.newInstance(BankStatementLineRow.class); } @Override
public DocumentId getId() { return rowId; } @Override public boolean isProcessed() { return isReconciled(); } @Override public DocumentPath getDocumentPath() { return null; } @Override public Set<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } static DocumentId convertBankStatementLineIdToDocumentId(@NonNull final BankStatementLineId bankStatementLineId) { return DocumentId.of(bankStatementLineId); } static BankStatementLineId convertDocumentIdToBankStatementLineId(@NonNull final DocumentId rowId) { return rowId.toId(BankStatementLineId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementLineRow.java
1
请完成以下Java代码
public class X_AD_User_Occupation_Job extends org.compiere.model.PO implements I_AD_User_Occupation_Job, org.compiere.model.I_Persistent { private static final long serialVersionUID = -804898259L; /** Standard Constructor */ public X_AD_User_Occupation_Job (final Properties ctx, final int AD_User_Occupation_Job_ID, @Nullable final String trxName) { super (ctx, AD_User_Occupation_Job_ID, trxName); } /** Load Constructor */ public X_AD_User_Occupation_Job (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_Occupation_Job_ID (final int AD_User_Occupation_Job_ID) { if (AD_User_Occupation_Job_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Job_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Job_ID, AD_User_Occupation_Job_ID); } @Override public int getAD_User_Occupation_Job_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_Job_ID); } @Override public org.compiere.model.I_CRM_Occupation getCRM_Occupation()
{ return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class); } @Override public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation) { set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation); } @Override public void setCRM_Occupation_ID (final int CRM_Occupation_ID) { if (CRM_Occupation_ID < 1) set_Value (COLUMNNAME_CRM_Occupation_ID, null); else set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID); } @Override public int getCRM_Occupation_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_Job.java
1
请完成以下Java代码
public void setM_Transaction_ID (int M_Transaction_ID) { if (M_Transaction_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Transaction_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Transaction_ID, Integer.valueOf(M_Transaction_ID)); } /** Get Bestands-Transaktion. @return Bestands-Transaktion */ @Override public int getM_Transaction_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Transaction_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_Cost_Collector getPP_Cost_Collector() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class); } @Override public void setPP_Cost_Collector(org.eevolution.model.I_PP_Cost_Collector PP_Cost_Collector) { set_ValueFromPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class, PP_Cost_Collector); } /** Set Manufacturing Cost Collector. @param PP_Cost_Collector_ID Manufacturing Cost Collector */ @Override
public void setPP_Cost_Collector_ID (int PP_Cost_Collector_ID) { if (PP_Cost_Collector_ID < 1) set_Value (COLUMNNAME_PP_Cost_Collector_ID, null); else set_Value (COLUMNNAME_PP_Cost_Collector_ID, Integer.valueOf(PP_Cost_Collector_ID)); } /** Get Manufacturing Cost Collector. @return Manufacturing Cost Collector */ @Override public int getPP_Cost_Collector_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Cost_Collector_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Transaction.java
1
请在Spring Boot框架中完成以下Java代码
public class Country { @Id private Long id; private String iso; private String name; private String emoji; public Country(Long id, String iso, String name, String emoji) { this.id = id; this.iso = iso; this.name = name; this.emoji = emoji; } public Country() { }
public Long getId() { return id; } public String getIso() { return iso; } public String getName() { return name; } public String getEmoji() { return emoji; } }
repos\tutorials-master\docker-modules\docker-multi-module-maven\domain\src\main\java\com\baeldung\domain\Country.java
2
请完成以下Java代码
public class SupplementaryDataEnvelope1 { @XmlAnyElement(lax = true) protected Object any; /** * Gets the value of the any property. * * @return * possible object is * {@link Element } * {@link Object } * */ public Object getAny() { return any; }
/** * Sets the value of the any property. * * @param value * allowed object is * {@link Element } * {@link Object } * */ public void setAny(Object value) { this.any = 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\SupplementaryDataEnvelope1.java
1
请完成以下Java代码
public String getCredentialId() { return credentialId; } public void setCredentialId(String credentialId) { this.credentialId = credentialId; } public String getPublicKeyCose() { return publicKeyCose; } public void setPublicKeyCose(String publicKeyCose) { this.publicKeyCose = publicKeyCose; } public Long getSignatureCount() { return signatureCount; } public void setSignatureCount(Long signatureCount) { this.signatureCount = signatureCount; } public Boolean getUvInitialized() { return uvInitialized; } public void setUvInitialized(Boolean uvInitialized) { this.uvInitialized = uvInitialized; } public String getTransports() { return transports; } public void setTransports(String transports) { this.transports = transports; } public Boolean getBackupEligible() { return backupEligible; } public void setBackupEligible(Boolean backupEligible) { this.backupEligible = backupEligible;
} public Boolean getBackupState() { return backupState; } public void setBackupState(Boolean backupState) { this.backupState = backupState; } public String getAttestationObject() { return attestationObject; } public void setAttestationObject(String attestationObject) { this.attestationObject = attestationObject; } public Instant getLastUsed() { return lastUsed; } public void setLastUsed(Instant lastUsed) { this.lastUsed = lastUsed; } public Instant getCreated() { return created; } public void setCreated(Instant created) { this.created = created; } }
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\domain\PasskeyCredential.java
1
请完成以下Java代码
public IQueryOrderByBuilder<T> addColumn(@NonNull final ModelColumn<T, ?> column, final Direction direction, final Nulls nulls) { final String columnName = column.getColumnName(); return addColumn(columnName, direction, nulls); } private Nulls getNulls(final Direction direction) { // NOTE: keeping backward compatibility // i.e. postgresql 9.1. specifications: // "By default, null values sort as if larger than any non-null value; // that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise." // // see https://www.postgresql.org/docs/9.5/queries-order.html if (direction == Direction.Descending)
{ return Nulls.First; } else { return Nulls.Last; } } @Override public IQueryOrderBy createQueryOrderBy() { final QueryOrderBy orderBy = new QueryOrderBy(orderBys); return orderBy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryOrderByBuilder.java
1
请完成以下Java代码
public RequestTypeId retrieveDefaultRequestTypeIdOrFirstActive() { return Optionals.firstPresentOfSuppliers( this::retrieveDefaultRequestTypeId, this::retrieveFirstActiveRequestTypeId) .orElseThrow(() -> new AdempiereException("@NotFound@ @R_RequestType_ID@").markAsUserValidationError()); } private Optional<RequestTypeId> retrieveDefaultRequestTypeId() { final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_R_RequestType.COLUMNNAME_IsDefault, true) .create() .firstIdOnly(RequestTypeId::ofRepoIdOrNull); return Optional.ofNullable(requestTypeId); } private Optional<RequestTypeId> retrieveFirstActiveRequestTypeId() {
final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .orderBy(I_R_RequestType.COLUMNNAME_R_RequestType_ID) .create() .firstId(RequestTypeId::ofRepoIdOrNull); return Optional.ofNullable(requestTypeId); } @Override public I_R_RequestType getById(@NonNull final RequestTypeId requestTypeId) { return queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addEqualsFilter(I_R_RequestType.COLUMNNAME_R_RequestType_ID, requestTypeId) .create() .firstOnlyNotNull(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\request\api\impl\RequestTypeDAO.java
1
请在Spring Boot框架中完成以下Java代码
public void downLoadFiles(String id, HttpServletRequest request, HttpServletResponse response) { // 参数校验 if (oConvertUtils.isEmpty(id)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } // 获取文章信息 SysAnnouncement sysAnnouncement = this.baseMapper.selectById(id); if (oConvertUtils.isEmpty(sysAnnouncement)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } //设置HTTP响应头:准备文件下载 response.reset(); response.setCharacterEncoding("utf-8"); response.setContentType("application/force-download"); ZipArchiveOutputStream zous = null; try { // 生成ZIP文件名:使用文章标题+时间戳避免重名 String title = sysAnnouncement.getTitile() + new Date().getTime(); String zipName = URLEncoder.encode( title + ".zip", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + zipName); // 创建ZIP输出流:直接输出到HTTP响应流 zous = new ZipArchiveOutputStream(response.getOutputStream()); zous.setUseZip64(Zip64Mode.AsNeeded);// 支持大文件 // 批量下载文件 String[] fileUrls = sysAnnouncement.getFiles().split(","); // 遍历所有文件URL for (int i = 0; i < fileUrls.length; i++) { String fileUrl = fileUrls[i].trim(); if (oConvertUtils.isEmpty(fileUrl)) { continue; } // 生成ZIP内文件名:避免重名,添加序号 String fileName = FileDownloadUtils.generateFileName(fileUrl, i, fileUrls.length);
String uploadUrl = jeecgBaseConfig.getPath().getUpload(); // 下载单个文件并添加到ZIP FileDownloadUtils.downLoadSingleFile(fileUrl,fileName,uploadUrl, zous); } // 完成ZIP写入 zous.finish(); // 刷新缓冲区确保数据发送 response.flushBuffer(); } catch (IOException e) { log.error("文件下载失败"+e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // 确保流关闭,防止资源泄漏 IoUtil.close(zous); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysAnnouncementServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
protected boolean isValidValueForResumePreviousBy(String resumePreviousBy) { return resumePreviousBy.equals(ResumePreviousBy.RESUME_BY_DEPLOYMENT_NAME) || resumePreviousBy.equals(ResumePreviousBy.RESUME_BY_PROCESS_DEFINITION_KEY); } /** * @param deploymentMap2 * @param deploymentName */ protected void logDeploymentSummary(Collection<String> resourceNames, String deploymentName, String processApplicationName) { // log a summary of the deployment StringBuilder builder = new StringBuilder(); builder.append("Deployment summary for process archive '"+deploymentName+"' of process application '"+processApplicationName+"': \n"); builder.append("\n"); for (String resourceName : resourceNames) { builder.append(" "+resourceName); builder.append("\n"); } LOGGER.log(Level.INFO, builder.toString()); } protected void performUndeployment() { final ProcessEngine processEngine = processEngineSupplier.get(); try { if(deployment != null) { // always unregister Set<String> deploymentIds = deployment.getProcessApplicationRegistration().getDeploymentIds(); processEngine.getManagementService().unregisterProcessApplication(deploymentIds, true); } } catch(Exception e) { LOGGER.log(Level.SEVERE, "Exception while unregistering process application with the process engine."); } // delete the deployment only if requested in metadata if(deployment != null && PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_DELETE_UPON_UNDEPLOY, false)) { try { LOGGER.info("Deleting cascade deployment with name '"+deployment.getName()+"/"+deployment.getId()+"'."); // always cascade & skip custom listeners processEngine.getRepositoryService().deleteDeployment(deployment.getId(), true, true); } catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception while deleting process engine deployment", e); } } } @Override public ProcessApplicationDeploymentService getValue() throws IllegalStateException, IllegalArgumentException { return this; } public ProcessApplicationDeployment getDeployment() { return deployment; } public String getProcessEngineName() { return processEngineSupplier.get().getName(); } public Supplier<ProcessEngine> getProcessEngineSupplier() { return processEngineSupplier; } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ProcessApplicationDeploymentService.java
2
请完成以下Java代码
public void setSuspended(Boolean suspended) { this.suspended = suspended; } protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } protected BatchQuery createNewQuery(ProcessEngine engine) { return engine.getManagementService().createBatchQuery(); } protected void applyFilters(BatchQuery query) { if (batchId != null) { query.batchId(batchId); } if (type != null) { query.type(type); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); }
if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(suspended)) { query.suspended(); } if (FALSE.equals(suspended)) { query.active(); } } protected void applySortBy(BatchQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { query.orderById(); } else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public class TelemetryRestServiceImpl extends AbstractRestProcessEngineAware implements TelemetryRestService { public TelemetryRestServiceImpl(String engineName, ObjectMapper objectMapper) { super(engineName, objectMapper); } @Override public void configureTelemetry(TelemetryConfigurationDto dto) { boolean enableTelemetry = dto.isEnableTelemetry(); ManagementService managementService = getProcessEngine().getManagementService(); managementService.toggleTelemetry(enableTelemetry); } @Override
public TelemetryConfigurationDto getTelemetryConfiguration() { ManagementService managementService = getProcessEngine().getManagementService(); Boolean telemetryEnabled = managementService.isTelemetryEnabled(); return new TelemetryConfigurationDto(telemetryEnabled); } @Override public TelemetryDataDto getTelemetryData() { ManagementService managementService = getProcessEngine().getManagementService(); TelemetryData data = managementService.getTelemetryData(); return TelemetryDataDto.fromEngineDto(data); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\TelemetryRestServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public StringToLocalDateConverter stringToLocalDateConverter() { return new StringToLocalDateConverter(); } @Bean public LocalDateToStringConverter localDateToStringConverter() { return new LocalDateToStringConverter(); } @Bean public StringToListConverter sringToListConverter(@Lazy ObjectMapper objectMapper) { return new StringToListConverter(objectMapper); } @Bean public ListToStringConverter listToStringConverter(@Lazy ObjectMapper objectMapper) { return new ListToStringConverter(objectMapper); } @Bean public StringToSetConverter stringToSetConverter(@Lazy ObjectMapper objectMapper) { return new StringToSetConverter(objectMapper); }
@Bean public SetToStringConverter setToStringConverter(@Lazy ObjectMapper objectMapper) { return new SetToStringConverter(objectMapper); } @Bean public StringToObjectValueConverter stringToObjectValueConverter(@Lazy ObjectMapper objectMapper) { return new StringToObjectValueConverter(objectMapper); } @Bean public ObjectValueToStringConverter objectValueToStringConverter(@Lazy ObjectMapper objectMapper) { return new ObjectValueToStringConverter(objectMapper); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\conf\impl\ProcessModelAutoConfiguration.java
2
请完成以下Java代码
public String translate(final Properties ctx, final String text) { return text; } @Override public String translate(final String adLanguage, final String text) { return text; } @Override public String translate(final Properties ctx, final String text, final boolean isSOTrx) { return text; } @Override public ITranslatableString translatable(final String text) { return TranslatableStrings.constant(text); } @Override public ITranslatableString getTranslatableMsgText(@NonNull final AdMessageKey adMessage, final Object... msgParameters) { if (msgParameters == null || msgParameters.length == 0) { return TranslatableStrings.constant(adMessage.toAD_Message()); } else { return TranslatableStrings.constant(adMessage.toAD_Message() + " - " + Joiner.on(", ").useForNull("-").join(msgParameters)); } } @Override public void cacheReset() { // nothing }
@Override public String getBaseLanguageMsg(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters) { return TranslatableStrings.adMessage(adMessage, msgParameters) .translate(Language.getBaseAD_Language()); } @Override public Optional<AdMessageId> getIdByAdMessage(@NonNull final AdMessageKey value) { return Optional.empty(); } @Override public boolean isMessageExists(final AdMessageKey adMessage) { return false; } @Override public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId) { return Optional.empty(); } @Nullable @Override public String getErrorCode(final @NonNull AdMessageKey messageKey) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\PlainMsgBL.java
1
请完成以下Java代码
public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public byte[] getBytes() { return bytes; } @Override public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public String getDeploymentId() { return deploymentId; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Object getPersistentState() { return ResourceEntityImpl.class;
} @Override public void setGenerated(boolean generated) { this.generated = generated; } /** * Indicated whether or not the resource has been generated while deploying rather than being actual part of the deployment. */ @Override public boolean isGenerated() { return generated; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "ResourceEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ResourceEntityImpl.java
1
请完成以下Java代码
public <T extends RepoIdAware> Optional<T> getValueAsId(@NonNull final String keyColumnName, @NonNull final Class<T> type) { return getValueAsInteger(keyColumnName).map(repoId -> RepoIdAwares.ofRepoIdOrNull(repoId, type)); } /** * @return all values (including nulls) in the same order as the key column names are */ public ArrayList<Object> getSqlValuesList() { final ArrayList<Object> allValuesIncludingNulls = new ArrayList<>(keyColumnNames.size()); for (final String keyColumnName : keyColumnNames) { final Object value = getValue(keyColumnName); allValuesIncludingNulls.add(value); } return allValuesIncludingNulls; } public void forEach(@NonNull final BiConsumer<String, Object> keyAndValueConsumer) { for (final String keyColumnName : keyColumnNames) { final Object value = getValue(keyColumnName); keyAndValueConsumer.accept(keyColumnName, value); } } public SqlAndParams getSqlValuesCommaSeparated() { final SqlAndParams.Builder sqlBuilder = SqlAndParams.builder(); for (final String keyColumnName : keyColumnNames) { final Object value = getValue(keyColumnName); if (!sqlBuilder.isEmpty()) { sqlBuilder.append(", "); } sqlBuilder.append("?", value); }
return sqlBuilder.build(); } public String getSqlWhereClauseById(@NonNull final String tableAlias) { final StringBuilder sql = new StringBuilder(); for (final String keyFieldName : keyColumnNames) { final Object idPart = getValue(keyFieldName); if (sql.length() > 0) { sql.append(" AND "); } sql.append(tableAlias).append(".").append(keyFieldName); if (!JSONNullValue.isNull(idPart)) { sql.append("=").append(DB.TO_SQL(idPart)); } else { sql.append(" IS NULL"); } } return sql.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlComposedKey.java
1
请完成以下Java代码
public String say() { return "Hello!" + this.getClass().getName(); } public InitBeanAndDestroyBean() { System.out.println("执行InitBeanAndDestroyBean构造方法"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void destroy() throws Exception { System.out.println("接口-执行InitBeanAndDestroyBeanTest:destroy方法"); } /** * Bean所有属性设置完(初始化完)之后调用 * * @throws Exception Exception */ @Override public void afterPropertiesSet() throws Exception { System.out.println("接口-执行InitBeanAndDestroyBeanTest:afterPropertiesSet方法"); } @PostConstruct
public void postConstructstroy() { System.out.println("注解-执行InitBeanAndDestroyBeanTest:preDestroy方法"); } @PreDestroy public void preDestroy() { System.out.println("注解--执行InitBeanAndDestroyBeanTest:preDestroy方法"); } /** * 真正的Bean初始化方法 */ public void initMethod() { System.out.println("XML配置-执行InitBeanAndDestroyBeanTest:init-method方法"); } /** * 真正的Bean销毁方法 */ public void destroyMethod() { System.out.println("XML配置-执行InitBeanAndDestroyBeanTest:destroy-method方法"); } }
repos\spring-boot-student-master\spring-boot-student-spring\src\main\java\com\xiaolyuh\init\destory\InitBeanAndDestroyBean.java
1
请完成以下Java代码
public void setFieldExtensions(List<FieldExtension> fieldExtensions) { this.fieldExtensions = fieldExtensions; } public String getMessageRef() { return messageRef; } public void setMessageRef(String messageRef) { this.messageRef = messageRef; } public String getMessageExpression() { return messageExpression; } public void setMessageExpression(String messageExpression) { this.messageExpression = messageExpression; } public String getCorrelationKey() { return correlationKey; }
public void setCorrelationKey(String correlationKey) { this.correlationKey = correlationKey; } public MessageEventDefinition clone() { MessageEventDefinition clone = new MessageEventDefinition(); clone.setValues(this); return clone; } public void setValues(MessageEventDefinition otherDefinition) { super.setValues(otherDefinition); setMessageRef(otherDefinition.getMessageRef()); setMessageExpression(otherDefinition.getMessageExpression()); setFieldExtensions(otherDefinition.getFieldExtensions()); setCorrelationKey(otherDefinition.getCorrelationKey()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MessageEventDefinition.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 设置realm. securityManager.setRealm(myShiroRealm()); //注入缓存管理器 securityManager.setCacheManager(ehCacheManager()); /* * 关闭shiro自带的session,详情见文档 * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29 */ DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO(); DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator(); defaultSessionStorageEvaluator.setSessionStorageEnabled(false); subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator); securityManager.setSubjectDAO(subjectDAO); return securityManager; } /** * 身份认证realm; (这个需要自己写,账号密码校验;权限等) */ @Bean public MyShiroRealm myShiroRealm() { MyShiroRealm myShiroRealm = new MyShiroRealm(); return myShiroRealm; } /** * 开启shiro aop注解支持. 使用代理方式; 所以需要开启代码支持; * * @param securityManager 安全管理器 * @return 授权Advisor */ @Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } /** * shiro缓存管理器; * 需要注入对应的其它的实体类中: * 1、安全管理器:securityManager * 可见securityManager是整个shiro的核心; * * @return */ @Bean public EhCacheManager ehCacheManager() { EhCacheManager cacheManager = new EhCacheManager(); cacheManager.setCacheManagerConfigFile("classpath:ehcache.xml"); return cacheManager; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\config\ShiroConfig.java
2
请完成以下Spring Boot application配置
mybatis.type-aliases-package=com.neo.entity spring.datasource.druid.one.driverClassName = com.mysql.jdbc.Driver spring.datasource.druid.one.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8 spring.datasource.druid.one.username = root spring.datasource.druid.one.password = root spring.datasource.druid.two.driverClassName = com.mysql.jdbc.Driver spring.datasource.druid.two.url = jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8 spring.datasource.druid.two.username = root spring.datasource.druid.two.password = root # \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927\u94FE\u63A5\u6570 spring.datasource.druid.initial-size=3 spring.datasource.druid.min-idle=3 spring.datasource.druid.max-active=10 # \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4 spring.datasource.druid.max-wait=60000 # StatViewServlet \u914D\u7F6E spring.datasource.druid.stat-view-servlet.login-username=admin spring.datasource.druid.stat-view-servlet.login-password=admin # \u914D\u7F6EStatFilter spring.datasource.druid.filter.stat.log-slow-sql=true spring.
datasource.druid.filter.stat.slow-sql-millis=2000 # Druid \u6570\u636E\u6E90 1 \u914D\u7F6E\uFF0C\u7EE7\u627Fspring.datasource.druid.* \u914D\u7F6E\uFF0C\u76F8\u540C\u5219\u8986\u76D6 spring.datasource.druid.one.max-active=20 spring.datasource.druid.one.max-wait=10000 # Druid \u6570\u636E\u6E90 2 \u914D\u7F6E\uFF0C\u7EE7\u627Fspring.datasource.druid.* \u914D\u7F6E\uFF0C\u76F8\u540C\u5219\u8986\u76D6 spring.datasource.druid.two.max-active=30 spring.datasource.druid.two.max-wait=20000
repos\spring-boot-leaning-master\1.x\第08课:Mybatis Druid 多数据源\spring-boot-multi-mybatis-druid\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class HUsToIssueViewFactory extends HUEditorViewFactoryTemplate { public static final String Window_ID_String = "husToIssueOnProject"; public static final WindowId Window_ID = WindowId.fromJson(Window_ID_String); public static final String PARAM_HUsToIssueViewContext = "HUsToIssueViewContext"; private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); protected HUsToIssueViewFactory() { super(ImmutableList.of()); } public CreateViewRequest createViewRequest(@NonNull final HUsToIssueViewContext context) { return CreateViewRequest.builder(Window_ID) .addStickyFilters(createEligibleHUsFilter(context.getProductId())) .setParameter(PARAM_HUsToIssueViewContext, context) .build(); }
private DocumentFilter createEligibleHUsFilter( @NonNull final ProductId productId) { return HUIdsFilterHelper.createFilter( handlingUnitsBL.createHUQueryBuilder() .addOnlyWithProductId(productId) .addHUStatusToInclude(X_M_HU.HUSTATUS_Active) .setExcludeReserved()); } @Override protected void customizeHUEditorView(final HUEditorViewBuilder huViewBuilder) { huViewBuilder.assertParameterSet(PARAM_HUsToIssueViewContext); huViewBuilder.considerTableRelatedProcessDescriptors(false) .addAdditionalRelatedProcessDescriptor(createProcessDescriptor(HUsToIssueView_IssueHUs.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\hu_to_issue\HUsToIssueViewFactory.java
2
请在Spring Boot框架中完成以下Java代码
public class ReceiptEntity implements Serializable { /** 主键 */ private String id; /** 发票类型 */ private ReceiptTypeEnum receiptTypeEnum; /** 发票抬头 */ private String title; /** 纳税人识别号 */ private String taxpayerNo; /** 发票内容 */ private String content; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReceiptTypeEnum getReceiptTypeEnum() { return receiptTypeEnum; } public void setReceiptTypeEnum(ReceiptTypeEnum receiptTypeEnum) { this.receiptTypeEnum = receiptTypeEnum; } public String getTitle() { return title; } public void setTitle(String title) {
this.title = title; } public String getTaxpayerNo() { return taxpayerNo; } public void setTaxpayerNo(String taxpayerNo) { this.taxpayerNo = taxpayerNo; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "ReceiptEntity{" + "id='" + id + '\'' + ", receiptTypeEnum=" + receiptTypeEnum + ", title='" + title + '\'' + ", taxpayerNo='" + taxpayerNo + '\'' + ", content='" + content + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\ReceiptEntity.java
2
请完成以下Java代码
public abstract class AbstractCmmnManager { protected AppEngineConfiguration appEngineConfiguration; public AbstractCmmnManager(AppEngineConfiguration appEngineConfiguration) { this.appEngineConfiguration = appEngineConfiguration; } protected CommandContext getCommandContext() { return Context.getCommandContext(); } protected <T> T getSession(Class<T> sessionClass) { return getCommandContext().getSession(sessionClass); } protected DbSqlSession getDbSqlSession() { return getSession(DbSqlSession.class); } protected AppResourceEntityManager getAppResourceEntityManager() { return appEngineConfiguration.getAppResourceEntityManager(); }
protected AppDeploymentEntityManager getAppDeploymentEntityManager() { return appEngineConfiguration.getAppDeploymentEntityManager(); } protected AppDefinitionEntityManager getAppDefinitionEntityManager() { return appEngineConfiguration.getAppDefinitionEntityManager(); } protected VariableInstanceEntityManager getVariableInstanceEntityManager() { return appEngineConfiguration.getVariableServiceConfiguration().getVariableInstanceEntityManager(); } protected IdentityLinkEntityManager getIdentityLinkEntityManager() { return appEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkEntityManager(); } protected AppEngineConfiguration getappEngineConfiguration() { return appEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\AbstractCmmnManager.java
1
请完成以下Java代码
public boolean isEmpty() { return cache.size() == 0; } // isEmpty /** * @see java.util.Map#keySet() */ public Set<K> keySet() { return cache.asMap().keySet(); } // keySet /** * @see java.util.Map#size() */ @Override public long size() { return cache.size(); } // size /** * @see java.util.Map#values() */ public Collection<V> values() { return cache.asMap().values(); } // values @Override protected final void finalize() throws Throwable { // NOTE: to avoid memory leaks we need to programatically clear our internal state try (final IAutoCloseable ignored = CacheMDC.putCache(this)) { logger.debug("Running finalize");
cache.invalidateAll(); } } public CCacheStats stats() { final CacheStats guavaStats = cache.stats(); return CCacheStats.builder() .cacheId(cacheId) .name(cacheName) .labels(labels) .config(config) .debugAcquireStacktrace(debugAcquireStacktrace) // .size(cache.size()) .hitCount(guavaStats.hitCount()) .missCount(guavaStats.missCount()) .build(); } private boolean isNoCache() { return allowDisablingCacheByThreadLocal && ThreadLocalCacheController.instance.isNoCache(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCache.java
1
请完成以下Java代码
protected DelegateExecution getExecution(HistoricDecisionInstanceEntity event) { return Context.getCommandContext().getExecutionManager().findExecutionById(event.getExecutionId()); } protected DelegateCaseExecution getCaseExecution(HistoricDecisionInstanceEntity event) { return Context.getCommandContext().getCaseExecutionManager().findCaseExecutionById(event.getCaseExecutionId()); } protected Date calculateRemovalTime(HistoricDecisionInstanceEntity historicDecisionInstance, DecisionDefinition decisionDefinition) { return Context.getProcessEngineConfiguration() .getHistoryRemovalTimeProvider() .calculateRemovalTime(historicDecisionInstance, decisionDefinition); } protected void provideRemovalTime(HistoryEvent historyEvent) { String rootProcessInstanceId = historyEvent.getRootProcessInstanceId(); if (rootProcessInstanceId != null) { HistoricProcessInstanceEventEntity historicRootProcessInstance = getHistoricRootProcessInstance(rootProcessInstanceId); if (historicRootProcessInstance != null) { Date removalTime = historicRootProcessInstance.getRemovalTime();
historyEvent.setRemovalTime(removalTime); } } } protected boolean isHistoryRemovalTimeStrategyStart() { return HISTORY_REMOVAL_TIME_STRATEGY_START.equals(getHistoryRemovalTimeStrategy()); } protected String getHistoryRemovalTimeStrategy() { return Context.getProcessEngineConfiguration() .getHistoryRemovalTimeStrategy(); } protected HistoricProcessInstanceEventEntity getHistoricRootProcessInstance(String rootProcessInstanceId) { return Context.getCommandContext().getDbEntityManager() .selectById(HistoricProcessInstanceEventEntity.class, rootProcessInstanceId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultDmnHistoryEventProducer.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionName() { return processDefinitionName; } public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public String getTenantId() { return tenantId; }
public void setTenantId(String tenantId) { this.tenantId = tenantId; } public static HistoricTaskInstanceReportResultDto fromHistoricTaskInstanceReportResult(HistoricTaskInstanceReportResult taskReportResult) { HistoricTaskInstanceReportResultDto dto = new HistoricTaskInstanceReportResultDto(); dto.count = taskReportResult.getCount(); dto.processDefinitionKey = taskReportResult.getProcessDefinitionKey(); dto.processDefinitionId = taskReportResult.getProcessDefinitionId(); dto.processDefinitionName = taskReportResult.getProcessDefinitionName(); dto.taskName = taskReportResult.getTaskName(); dto.tenantId = taskReportResult.getTenantId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceReportResultDto.java
1
请完成以下Java代码
public void setPP_Plant_ID (final int PP_Plant_ID) { if (PP_Plant_ID < 1) set_Value (COLUMNNAME_PP_Plant_ID, null); else set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID); } @Override public int getPP_Plant_ID() { return get_ValueAsInt(COLUMNNAME_PP_Plant_ID); } @Override public void setReplenishmentClass (final @Nullable java.lang.String ReplenishmentClass) { set_Value (COLUMNNAME_ReplenishmentClass, ReplenishmentClass); } @Override public java.lang.String getReplenishmentClass() { return get_ValueAsString(COLUMNNAME_ReplenishmentClass); } @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); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override
public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse.java
1
请完成以下Java代码
public Collection<ComplexBehaviorDefinition> getComplexBehaviorDefinitions() { return complexBehaviorDefinitionCollection.get(this); } public CompletionCondition getCompletionCondition() { return completionConditionChild.getChild(this); } public void setCompletionCondition(CompletionCondition completionCondition) { completionConditionChild.setChild(this, completionCondition); } public boolean isSequential() { return isSequentialAttribute.getValue(this); } public void setSequential(boolean sequential) { isSequentialAttribute.setValue(this, sequential); } public MultiInstanceFlowCondition getBehavior() { return behaviorAttribute.getValue(this); } public void setBehavior(MultiInstanceFlowCondition behavior) { behaviorAttribute.setValue(this, behavior); } public EventDefinition getOneBehaviorEventRef() { return oneBehaviorEventRefAttribute.getReferenceTargetElement(this); } public void setOneBehaviorEventRef(EventDefinition oneBehaviorEventRef) { oneBehaviorEventRefAttribute.setReferenceTargetElement(this, oneBehaviorEventRef); } public EventDefinition getNoneBehaviorEventRef() { return noneBehaviorEventRefAttribute.getReferenceTargetElement(this); } public void setNoneBehaviorEventRef(EventDefinition noneBehaviorEventRef) { noneBehaviorEventRefAttribute.setReferenceTargetElement(this, noneBehaviorEventRef); } public boolean isCamundaAsyncBefore() { return camundaAsyncBefore.getValue(this); } public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) { camundaAsyncBefore.setValue(this, isCamundaAsyncBefore); } public boolean isCamundaAsyncAfter() { return camundaAsyncAfter.getValue(this);
} public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) { camundaAsyncAfter.setValue(this, isCamundaAsyncAfter); } public boolean isCamundaExclusive() { return camundaExclusive.getValue(this); } public void setCamundaExclusive(boolean isCamundaExclusive) { camundaExclusive.setValue(this, isCamundaExclusive); } public String getCamundaCollection() { return camundaCollection.getValue(this); } public void setCamundaCollection(String expression) { camundaCollection.setValue(this, expression); } public String getCamundaElementVariable() { return camundaElementVariable.getValue(this); } public void setCamundaElementVariable(String variableName) { camundaElementVariable.setValue(this, variableName); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MultiInstanceLoopCharacteristicsImpl.java
1
请完成以下Java代码
public PageData<User> findUsersByCustomerIds(UUID tenantId, List<CustomerId> customerIds, PageLink pageLink) { return DaoUtil.toPageData( userRepository .findTenantAndCustomerUsers( tenantId, DaoUtil.toUUIDs(customerIds), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public PageData<User> findAll(PageLink pageLink) { return DaoUtil.toPageData(userRepository.findAll(DaoUtil.toPageable(pageLink))); } @Override public PageData<User> findAllByAuthority(Authority authority, PageLink pageLink) { return DaoUtil.toPageData(userRepository.findAllByAuthority(authority, DaoUtil.toPageable(pageLink))); } @Override public PageData<User> findByAuthorityAndTenantsIds(Authority authority, List<TenantId> tenantsIds, PageLink pageLink) { return DaoUtil.toPageData(userRepository.findByAuthorityAndTenantIdIn(authority, DaoUtil.toUUIDs(tenantsIds), DaoUtil.toPageable(pageLink))); } @Override public PageData<User> findByAuthorityAndTenantProfilesIds(Authority authority, List<TenantProfileId> tenantProfilesIds, PageLink pageLink) { return DaoUtil.toPageData(userRepository.findByAuthorityAndTenantProfilesIds(authority, DaoUtil.toUUIDs(tenantProfilesIds), DaoUtil.toPageable(pageLink))); } @Override public UserAuthDetails findUserAuthDetailsByUserId(UUID tenantId, UUID userId) { TbPair<UserEntity, Boolean> result = userRepository.findUserAuthDetailsByUserId(userId); return result != null ? new UserAuthDetails(result.getFirst().toData(), result.getSecond()) : null; } @Override public int countTenantAdmins(UUID tenantId) {
return userRepository.countByTenantIdAndAuthority(tenantId, Authority.TENANT_ADMIN); } @Override public List<User> findUsersByTenantIdAndIds(UUID tenantId, List<UUID> userIds) { return DaoUtil.convertDataList(userRepository.findUsersByTenantIdAndIdIn(tenantId, userIds)); } @Override public Long countByTenantId(TenantId tenantId) { return userRepository.countByTenantId(tenantId.getId()); } @Override public PageData<User> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<UserFields> findNextBatch(UUID id, int batchSize) { return userRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.USER; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\user\JpaUserDao.java
1
请完成以下Java代码
public class Order { private UUID id; @JsonUnwrapped private Type type; private int internalAudit; public static class Type { public long id; public String name; } public Order() { this.id = UUID.randomUUID(); } public Order(Type type) { this(); this.type = type; } public Order(int internalAudit) { this();
this.type = new Type(); this.type.id = 20; this.type.name = "Order"; this.internalAudit = internalAudit; } public UUID getId() { return id; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } }
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\general\jsonunwrapped\Order.java
1
请完成以下Java代码
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 int getM_Product_Ingredients_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Ingredients_ID); } @Override public void setNRV (final int NRV) { set_Value (COLUMNNAME_NRV, NRV); } @Override public int getNRV() { return get_ValueAsInt(COLUMNNAME_NRV); } @Override public org.compiere.model.I_M_Ingredients getParentElement() { return get_ValueAsPO(COLUMNNAME_ParentElement_ID, org.compiere.model.I_M_Ingredients.class); } @Override public void setParentElement(final org.compiere.model.I_M_Ingredients ParentElement) { set_ValueFromPO(COLUMNNAME_ParentElement_ID, org.compiere.model.I_M_Ingredients.class, ParentElement); } @Override public void setParentElement_ID (final int ParentElement_ID) { if (ParentElement_ID < 1) set_Value (COLUMNNAME_ParentElement_ID, null); else set_Value (COLUMNNAME_ParentElement_ID, ParentElement_ID); } @Override public int getParentElement_ID() { return get_ValueAsInt(COLUMNNAME_ParentElement_ID); } @Override public void setPrecision (final int Precision) { set_Value (COLUMNNAME_Precision, Precision); } @Override
public int getPrecision() { return get_ValueAsInt(COLUMNNAME_Precision); } @Override public void setQty (final @Nullable java.lang.String Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public java.lang.String getQty() { return get_ValueAsString(COLUMNNAME_Qty); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Ingredients.java
1
请完成以下Java代码
public void setTokenType (String TokenType) { set_Value (COLUMNNAME_TokenType, TokenType); } /** Get TokenType. @return Wiki Token Type */ public String getTokenType () { return (String)get_Value(COLUMNNAME_TokenType); } /** Set Sql WHERE.
@param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WikiToken.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?cachePrepStmts=true&useServerPrepStmts=true&rewriteBatchedStatements=true&createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.open-in-view=false spring.jpa.properties.hibernate.jdbc.batch_size=30 spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true # this is n
eeded for ordering updates in case of relationships spring.jpa.properties.hibernate.order_updates=true spring.jpa.properties.hibernate.cache.use_second_level_cache=false spring.jpa.properties.hibernate.generate_statistics=true
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchUpdateOrder\src\main\resources\application.properties
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer("MPrintColor["); sb.append("ID=").append(get_ID()) .append(",Name=").append(getName()) .append(",RGB=").append(getCode()) .append(",").append(getColor()) .append("]"); return sb.toString(); } // toString /************************************************************************** * Create Standard Colors * @param args args */ public static void main(String[] args) { org.compiere.Adempiere.startupEnvironment(true); Color[] colors = new Color[] {Color.black, Color.red, Color.green, Color.blue, Color.darkGray, Color.gray, Color.lightGray, Color.white, Color.cyan, Color.magenta, Color.orange, Color.pink, Color.yellow, SystemColor.textHighlight}; String[] names = new String[] {"Black", "Red", "Green", "Blue", "Gray dark", "Gray", "Gray light", "White", "Cyan", "Magenta", "Orange", "Pink", "Yellow", "Blue dark"}; for (int i = 0; i < colors.length; i++) System.out.println(names[i] + " = " + colors[i] + " RGB=" + colors[i].getRGB() + " -> " + new Color(colors[i].getRGB(), false) + " -> " + new Color(colors[i].getRGB(), true));
/** // Create Colors for (int i = 0; i < colors.length; i++) create(colors[i], names[i]); create(whiteGray, "Gray white"); create(darkGreen, "Green dark"); create(blackGreen, "Green black"); create(blackBlue, "Blue black"); create(brown, "Brown"); create(darkBrown, "Brown dark"); **/ // Read All Colors int[] IDs = PO.getAllIDs ("AD_PrintColor", null, null); for (int i = 0; i < IDs.length; i++) { MPrintColor pc = new MPrintColor(Env.getCtx(), IDs[i], null); System.out.println(IDs[i] + ": " + pc + " = " + pc.getColor() + ", RGB=" + pc.getColor().getRGB()); } } // main } // MPrintColor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintColor.java
1
请完成以下Java代码
public String getImplementation() { return implementationAttribute.getValue(this); } public void setImplementation(String implementation) { implementationAttribute.setValue(this, implementation); } public boolean instantiate() { return instantiateAttribute.getValue(this); } public void setInstantiate(boolean instantiate) { instantiateAttribute.setValue(this, instantiate); }
public Message getMessage() { return messageRefAttribute.getReferenceTargetElement(this); } public void setMessage(Message message) { messageRefAttribute.setReferenceTargetElement(this, message); } public Operation getOperation() { return operationRefAttribute.getReferenceTargetElement(this); } public void setOperation(Operation operation) { operationRefAttribute.setReferenceTargetElement(this, operation); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ReceiveTaskImpl.java
1
请完成以下Java代码
public boolean isEvaluateRepetitionRule() { // by default, we don't create new instances for repeatable plan items being terminated, however, if the exit type is set to only terminate active or // enabled instances, we might want to immediately create a new instance for repetition, but only, if the current one was terminated, of course return (EXIT_TYPE_ACTIVE_INSTANCES.equals(exitType) || EXIT_TYPE_ACTIVE_AND_ENABLED_INSTANCES.equals(exitType)) && TERMINATED.equals(getNewState()); } @Override protected Map<String, String> getAsyncLeaveTransitionMetadata() { Map<String, String> metadata = new HashMap<>(); metadata.put(OperationSerializationMetadata.FIELD_PLAN_ITEM_INSTANCE_ID, planItemInstanceEntity.getId()); metadata.put(OperationSerializationMetadata.FIELD_EXIT_CRITERION_ID, exitCriterionId); metadata.put(OperationSerializationMetadata.FIELD_EXIT_TYPE, exitType); metadata.put(OperationSerializationMetadata.FIELD_EXIT_EVENT_TYPE, exitEventType); metadata.put(OperationSerializationMetadata.FIELD_IS_STAGE, isStage != null ? isStage.toString() : Boolean.FALSE.toString()); return metadata; } @Override protected boolean shouldAggregateForSingleInstance() { return false; } @Override protected boolean shouldAggregateForMultipleInstances() { return false; } public boolean isStage() { if (isStage == null) { isStage = isStage(planItemInstanceEntity); } return isStage; } @Override public String getOperationName() { return "[Exit plan item]"; } public String getExitCriterionId() { return exitCriterionId; }
public void setExitCriterionId(String exitCriterionId) { this.exitCriterionId = exitCriterionId; } public String getExitType() { return exitType; } public void setExitType(String exitType) { this.exitType = exitType; } public String getExitEventType() { return exitEventType; } public void setExitEventType(String exitEventType) { this.exitEventType = exitEventType; } public Boolean getStage() { return isStage; } public void setStage(Boolean stage) { isStage = stage; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ExitPlanItemInstanceOperation.java
1
请完成以下Java代码
private I_C_Invoice_Detail syncToRecord( @NonNull final OrgId orgId, @NonNull final InvoiceDetailItem invoiceDetailItem, @Nullable final I_C_Invoice_Detail existingInvoiceDetailRecord) { final I_C_Invoice_Detail recordToUpdate; if (existingInvoiceDetailRecord == null) { recordToUpdate = InterfaceWrapperHelper.newInstance(I_C_Invoice_Detail.class); } else { recordToUpdate = existingInvoiceDetailRecord; } final ZoneId timeZone = orgDAO.getTimeZone(orgId); recordToUpdate.setAD_Org_ID(orgId.getRepoId()); recordToUpdate.setLabel(invoiceDetailItem.getLabel()); recordToUpdate.setDescription(invoiceDetailItem.getDescription()); recordToUpdate.setDate(TimeUtil.asTimestamp(invoiceDetailItem.getDate(), timeZone)); return recordToUpdate; } @Value private static class StagingRecordKey { @Nullable InvoiceId invoiceId; @Nullable InvoiceAndLineId invoiceAndLineId; @NonNull String label; public static StagingRecordKey forRecordOrNull(@NonNull final I_C_Invoice_Detail detailRecord) { final InvoiceAndLineId invoiceAndLineId = InvoiceAndLineId.ofRepoIdOrNull(detailRecord.getC_Invoice_ID(), detailRecord.getC_InvoiceLine_ID()); if (invoiceAndLineId != null) { return new StagingRecordKey(null, invoiceAndLineId, detailRecord.getLabel()); } final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(detailRecord.getC_Invoice_ID()); if (invoiceId != null)
{ return new StagingRecordKey(invoiceId, null, detailRecord.getLabel()); } return null; } public static StagingRecordKey forItemOrNull(@NonNull final InvoiceId invoiceId, @NonNull final InvoiceDetailItem detailItem) { return new StagingRecordKey(invoiceId, null, detailItem.getLabel()); } public static StagingRecordKey forItemOrNull(@NonNull final InvoiceAndLineId invoiceAndLineId, @NonNull final InvoiceDetailItem detailItem) { return new StagingRecordKey(null, invoiceAndLineId, detailItem.getLabel()); } } // also used by InvoiceWithDetailsService List<I_C_Invoice_Detail> getInvoiceDetailsListForInvoiceId(@NonNull final InvoiceId invoiceId) { return queryBL .createQueryBuilder(I_C_Invoice_Detail.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice_Detail.COLUMNNAME_C_Invoice_ID, invoiceId) .create() .list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\detail\InvoiceWithDetailsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class ConditionMessageRepresentation { private String condition; private String data; /** * @return the condition */ public String getCondition() { return condition; } /** * @param condition the condition to set */ public void setCondition(String condition) { this.condition = condition;
} /** * @return the data */ public String getData() { return data; } /** * @param data the data to set */ public void setData(String data) { this.data = data; } }
repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\publisher\controller\ConditionMessageRepresentation.java
2
请完成以下Java代码
public long getPriority() { return priority; } public String getErrorDetails() { return errorDetails; } public String getBusinessKey() { return businessKey; } public Map<String, String> getExtensionProperties(){ return extensionProperties; } public static LockedExternalTaskDto fromLockedExternalTask(LockedExternalTask task) { LockedExternalTaskDto dto = new LockedExternalTaskDto(); dto.activityId = task.getActivityId(); dto.activityInstanceId = task.getActivityInstanceId(); dto.errorMessage = task.getErrorMessage(); dto.errorDetails = task.getErrorDetails(); dto.executionId = task.getExecutionId(); dto.id = task.getId(); dto.lockExpirationTime = task.getLockExpirationTime(); dto.createTime = task.getCreateTime(); dto.processDefinitionId = task.getProcessDefinitionId(); dto.processDefinitionKey = task.getProcessDefinitionKey(); dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag(); dto.processInstanceId = task.getProcessInstanceId(); dto.retries = task.getRetries(); dto.topicName = task.getTopicName(); dto.workerId = task.getWorkerId(); dto.tenantId = task.getTenantId(); dto.variables = VariableValueDto.fromMap(task.getVariables()); dto.priority = task.getPriority(); dto.businessKey = task.getBusinessKey(); dto.extensionProperties = task.getExtensionProperties(); return dto; } public static List<LockedExternalTaskDto> fromLockedExternalTasks(List<LockedExternalTask> tasks) { List<LockedExternalTaskDto> dtos = new ArrayList<>();
for (LockedExternalTask task : tasks) { dtos.add(LockedExternalTaskDto.fromLockedExternalTask(task)); } return dtos; } @Override public String toString() { return "LockedExternalTaskDto [activityId=" + activityId + ", activityInstanceId=" + activityInstanceId + ", errorMessage=" + errorMessage + ", errorDetails=" + errorDetails + ", executionId=" + executionId + ", id=" + id + ", lockExpirationTime=" + lockExpirationTime + ", createTime=" + createTime + ", processDefinitionId=" + processDefinitionId + ", processDefinitionKey=" + processDefinitionKey + ", processDefinitionVersionTag=" + processDefinitionVersionTag + ", processInstanceId=" + processInstanceId + ", retries=" + retries + ", suspended=" + suspended + ", workerId=" + workerId + ", topicName=" + topicName + ", tenantId=" + tenantId + ", variables=" + variables + ", priority=" + priority + ", businessKey=" + businessKey + "]"; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\LockedExternalTaskDto.java
1
请完成以下Java代码
public class CardholderAuthentication2 { @XmlElement(name = "AuthntcnMtd", required = true) @XmlSchemaType(name = "string") protected AuthenticationMethod1Code authntcnMtd; @XmlElement(name = "AuthntcnNtty", required = true) @XmlSchemaType(name = "string") protected AuthenticationEntity1Code authntcnNtty; /** * Gets the value of the authntcnMtd property. * * @return * possible object is * {@link AuthenticationMethod1Code } * */ public AuthenticationMethod1Code getAuthntcnMtd() { return authntcnMtd; } /** * Sets the value of the authntcnMtd property. * * @param value * allowed object is * {@link AuthenticationMethod1Code } * */ public void setAuthntcnMtd(AuthenticationMethod1Code value) { this.authntcnMtd = value; } /**
* Gets the value of the authntcnNtty property. * * @return * possible object is * {@link AuthenticationEntity1Code } * */ public AuthenticationEntity1Code getAuthntcnNtty() { return authntcnNtty; } /** * Sets the value of the authntcnNtty property. * * @param value * allowed object is * {@link AuthenticationEntity1Code } * */ public void setAuthntcnNtty(AuthenticationEntity1Code value) { this.authntcnNtty = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\CardholderAuthentication2.java
1
请完成以下Java代码
public int hashCode() { return Objects.hash(name, age); } private String name; private int age; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; public Long getId() { return id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\flush\Customer.java
1
请完成以下Java代码
public class X_M_RMAType extends PO implements I_M_RMAType, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_M_RMAType (Properties ctx, int M_RMAType_ID, String trxName) { super (ctx, M_RMAType_ID, trxName); /** if (M_RMAType_ID == 0) { setM_RMAType_ID (0); setName (null); } */ } /** Load Constructor */ public X_M_RMAType (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 2 - Client */ 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_RMAType[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint
*/ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set RMA Type. @param M_RMAType_ID Return Material Authorization Type */ public void setM_RMAType_ID (int M_RMAType_ID) { if (M_RMAType_ID < 1) set_ValueNoCheck (COLUMNNAME_M_RMAType_ID, null); else set_ValueNoCheck (COLUMNNAME_M_RMAType_ID, Integer.valueOf(M_RMAType_ID)); } /** Get RMA Type. @return Return Material Authorization Type */ public int getM_RMAType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_RMAType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RMAType.java
1
请在Spring Boot框架中完成以下Java代码
public class GroupResource extends BaseGroupResource { @ApiOperation(value = "Get a single group", tags = { "Groups" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the group exists and is returned."), @ApiResponse(code = 404, message = "Indicates the requested group does not exist.") }) @GetMapping(value = "/groups/{groupId}", produces = "application/json") public GroupResponse getGroup(@ApiParam(name = "groupId") @PathVariable String groupId) { return restResponseFactory.createGroupResponse(getGroupFromRequest(groupId)); } @ApiOperation(value = "Update a group", tags = { "Groups" }, notes = "All request values are optional. For example, you can only include the name attribute in the request body JSON-object, only updating the name of the group, leaving all other fields unaffected. When an attribute is explicitly included and is set to null, the group-value will be updated to null.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the group was updated."), @ApiResponse(code = 404, message = "Indicates the requested group was not found."), @ApiResponse(code = 409, message = "Indicates the requested group was updated simultaneously.") }) @PutMapping(value = "/groups/{groupId}", produces = "application/json") public GroupResponse updateGroup(@ApiParam(name = "groupId") @PathVariable String groupId, @RequestBody GroupRequest groupRequest) { Group group = getGroupFromRequest(groupId); if (groupRequest.getId() == null || groupRequest.getId().equals(group.getId())) { if (groupRequest.isNameChanged()) { group.setName(groupRequest.getName()); } if (groupRequest.isTypeChanged()) { group.setType(groupRequest.getType()); } identityService.saveGroup(group); } else { throw new FlowableIllegalArgumentException("Key provided in request body doesn't match the key in the resource URL."); } return restResponseFactory.createGroupResponse(group); }
@ApiOperation(value = "Delete a group", tags = { "Groups" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the group was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested group does not exist.") }) @DeleteMapping("/groups/{groupId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteGroup(@ApiParam(name = "groupId") @PathVariable String groupId) { Group group = getGroupFromRequest(groupId); if (restApiInterceptor != null) { restApiInterceptor.deleteGroup(group); } identityService.deleteGroup(group.getId()); } }
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\group\GroupResource.java
2
请完成以下Java代码
public <C> C mapInternalToJava(Object parameter, JavaType type) { return mapInternalToJava(parameter, type, null); } public <C> C mapInternalToJava(Object parameter, JavaType type, DeserializationTypeValidator validator) { JsonNode jsonNode = (JsonNode) parameter; try { validateType(type, validator); ObjectMapper mapper = format.getObjectMapper(); return mapper.readValue(mapper.treeAsTokens(jsonNode), type); } catch (IOException | SpinRuntimeException e) { throw LOG.unableToDeserialize(jsonNode, type, e); } } /** * Validate the type with the help of the validator.<br> * Note: when adjusting this method, please also consider adjusting * the {@code AbstractVariablesResource#validateType} in the REST API */ protected void validateType(JavaType type, DeserializationTypeValidator validator) { if (validator != null) { List<String> invalidTypes = new ArrayList<>(); validateType(type, validator, invalidTypes); if (!invalidTypes.isEmpty()) { throw new SpinRuntimeException("The following classes are not whitelisted for deserialization: " + invalidTypes); } } } protected void validateType(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) { if (!type.isPrimitive()) { if (!type.isArrayType()) { validateTypeInternal(type, validator, invalidTypes); }
if (type.isMapLikeType()) { validateType(type.getKeyType(), validator, invalidTypes); } if (type.isContainerType() || type.hasContentType()) { validateType(type.getContentType(), validator, invalidTypes); } } } protected void validateTypeInternal(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) { String className = type.getRawClass().getName(); if (!validator.validate(className) && !invalidTypes.contains(className)) { invalidTypes.add(className); } } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\JacksonJsonDataFormatMapper.java
1
请完成以下Java代码
public abstract class AbstractProcessDocumentsTemplate extends JavaProcess { // // services private final ITrxManager trxManager = Services.get(ITrxManager.class); private final IDocumentBL docActionBL = Services.get(IDocumentBL.class); private final IDocumentBL documentBL = Services.get(IDocumentBL.class); // // Statistics private int countOK = 0; private int countError = 0; @Override protected final String doIt() { this.countOK = 0; this.countError = 0; final Iterator<GenericPO> documents = retrieveDocumentsToProcess(); processDocuments(documents, getDocAction()); return "@Processed@ (OK=#" + countOK + ", Error=#" + countError + ")"; } protected abstract Iterator<GenericPO> retrieveDocumentsToProcess(); protected abstract String getDocAction(); private void processDocuments(final Iterator<GenericPO> documents, final String docAction) { while (documents.hasNext()) { final Object doc = documents.next(); trxManager.runInNewTrx(new TrxRunnable2() {
@Override public void run(final String localTrxName) { InterfaceWrapperHelper.refresh(doc, localTrxName); docActionBL.processEx(doc, docAction, null); // expectedDocStatus=null because it is *not* always equal to the docAaction (Prepay-Order) addLog("Document " + doc + ": Processed"); countOK++; } @Override public boolean doCatch(final Throwable e) { final String msg = "Processing of document " + doc + ": Failed - ProccessMsg: " + documentBL.getDocument(doc).getProcessMsg() + "; ExceptionMsg: " + e.getMessage(); addLog(msg); log.warn(msg, e); countError++; return true; // rollback } @Override public void doFinally() { // nothing } }); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\process\AbstractProcessDocumentsTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public void setComment(String comment) { this.comment = comment; } /** * @return the posted */ @JsonSerialize(using = CustomDateToLongSerializer.class) public Date getPosted() { return posted; } /** * @param posted * the posted to set */ public void setPosted(Date posted) { this.posted = posted; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((comment == null) ? 0 : comment.hashCode()); result = prime * result + ((posted == null) ? 0 : posted.hashCode()); result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CommentDTO other = (CommentDTO) obj; if (comment == null) { if (other.comment != null) return false; } else if (!comment.equals(other.comment)) return false; if (posted == null) { if (other.posted != null)
return false; } else if (!posted.equals(other.posted)) return false; if (taskId == null) { if (other.taskId != null) return false; } else if (!taskId.equals(other.taskId)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "CommentDTO [taskId=" + taskId + ", comment=" + comment + ", posted=" + posted + "]"; } } /** * Custom date serializer that converts the date to long before sending it out * * @author anilallewar * */ class CustomDateToLongSerializer extends JsonSerializer<Date> { @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeNumber(value.getTime()); } }
repos\spring-boot-microservices-master\comments-webservice\src\main\java\com\rohitghatol\microservices\comments\dtos\CommentDTO.java
2
请完成以下Java代码
public void getOrderResult(RpOrderResultQueryVo rpOrderResultQueryVo){ Integer notifyTimes = rpOrderResultQueryVo.getNotifyTimes(); // 得到当前通知对象的通知次数 Integer maxNotifyTimes = rpOrderResultQueryVo.getLimitNotifyTimes(); // 最大通知次数 Date notifyTime = new Date(); // 本次通知的时间 rpOrderResultQueryVo.setEditTime(notifyTime); // 取本次通知时间作为最后修改时间 rpOrderResultQueryVo.setNotifyTimes(notifyTimes + 1); // 通知次数+1 LOG.info("notifyTimes:{} , maxNotifyTimes:{} " ,notifyTimes , maxNotifyTimes); try{ boolean processingResult = rpTradePaymentManagerService.processingTradeRecord(rpOrderResultQueryVo.getBankOrderNo()); LOG.info("order processing result:{}" ,processingResult); if (!processingResult){//返回失败,说明还未支付 // 通知不成功(返回的结果不是success) if (rpOrderResultQueryVo.getNotifyTimes() < maxNotifyTimes) { // 判断是否超过重发次数,未超重发次数的,再次进入延迟发送队列 pollingQueue.addToNotifyTaskDelayQueue(rpOrderResultQueryVo); LOG.info("===>bank order {} need processing again ", rpOrderResultQueryVo.getBankOrderNo()); } else { LOG.info("bank order No {} not pay" , rpOrderResultQueryVo.getBankOrderNo()); } } }catch (BizException e){ LOG.error("订单处理业务异常:", e);
if (rpOrderResultQueryVo.getNotifyTimes() < maxNotifyTimes) { // 判断是否超过重发次数,未超重发次数的,再次进入延迟发送队列 pollingQueue.addToNotifyTaskDelayQueue(rpOrderResultQueryVo); LOG.info("===>bank order {} need processing again ", rpOrderResultQueryVo.getBankOrderNo()); } else { LOG.info("bank order No {} not pay" , rpOrderResultQueryVo.getBankOrderNo()); } }catch (Exception e){ LOG.error("订单处理系统异常:", e); if (rpOrderResultQueryVo.getNotifyTimes() < maxNotifyTimes) { // 判断是否超过重发次数,未超重发次数的,再次进入延迟发送队列 pollingQueue.addToNotifyTaskDelayQueue(rpOrderResultQueryVo); LOG.info("===>bank order {} need processing again ", rpOrderResultQueryVo.getBankOrderNo()); } else { LOG.info("bank order No {} not pay" , rpOrderResultQueryVo.getBankOrderNo()); } } } }
repos\roncoo-pay-master\roncoo-pay-app-order-polling\src\main\java\com\roncoo\pay\app\polling\core\PollingPersist.java
1
请完成以下Java代码
public boolean isShowNotDue () { Object oo = get_Value(COLUMNNAME_IsShowNotDue); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Is Statement. @param IsStatement Dunning Level is a definition of a statement */ @Override public void setIsStatement (boolean IsStatement) { set_Value (COLUMNNAME_IsStatement, Boolean.valueOf(IsStatement)); } /** Get Is Statement. @return Dunning Level is a definition of a statement */ @Override public boolean isStatement () { Object oo = get_Value(COLUMNNAME_IsStatement); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Massenaustritt. @param IsWriteOff Massenaustritt */ @Override public void setIsWriteOff (boolean IsWriteOff) { set_Value (COLUMNNAME_IsWriteOff, Boolean.valueOf(IsWriteOff)); } /** Get Massenaustritt. @return Massenaustritt */ @Override public boolean isWriteOff () { Object oo = get_Value(COLUMNNAME_IsWriteOff); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); }
/** Set Notiz. @param Note Optional additional user defined information */ @Override public void setNote (java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } /** Get Notiz. @return Optional additional user defined information */ @Override public java.lang.String getNote () { return (java.lang.String)get_Value(COLUMNNAME_Note); } /** Set Notiz Header. @param NoteHeader Optional weitere Information für ein Dokument */ @Override public void setNoteHeader (java.lang.String NoteHeader) { set_Value (COLUMNNAME_NoteHeader, NoteHeader); } /** Get Notiz Header. @return Optional weitere Information für ein Dokument */ @Override public java.lang.String getNoteHeader () { return (java.lang.String)get_Value(COLUMNNAME_NoteHeader); } /** Set Drucktext. @param PrintName The label text to be printed on a document or correspondence. */ @Override public void setPrintName (java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } /** Get Drucktext. @return The label text to be printed on a document or correspondence. */ @Override public java.lang.String getPrintName () { return (java.lang.String)get_Value(COLUMNNAME_PrintName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningLevel.java
1
请完成以下Java代码
public static <T, R> Collector<T, ?, R> collectUsingHashSetAccumulator(@NonNull final Function<HashSet<T>, R> finisher) { final Supplier<HashSet<T>> supplier = HashSet::new; final BiConsumer<HashSet<T>, T> accumulator = HashSet::add; final BinaryOperator<HashSet<T>> combiner = (acc1, acc2) -> { acc1.addAll(acc2); return acc1; }; return Collector.of(supplier, accumulator, combiner, finisher); } public static <T, R, K> Collector<T, ?, R> collectUsingMapAccumulator(@NonNull final Function<T, K> keyMapper, @NonNull final Function<Map<K, T>, R> finisher) { final Supplier<Map<K, T>> supplier = LinkedHashMap::new; final BiConsumer<Map<K, T>, T> accumulator = (map, item) -> map.put(keyMapper.apply(item), item); final BinaryOperator<Map<K, T>> combiner = (acc1, acc2) -> { acc1.putAll(acc2); return acc1; }; return Collector.of(supplier, accumulator, combiner, finisher); } public static <T, R, K, V> Collector<T, ?, R> collectUsingMapAccumulator( @NonNull final Function<T, K> keyMapper, @NonNull final Function<T, V> valueMapper, @NonNull final Function<Map<K, V>, R> finisher) { final Supplier<Map<K, V>> supplier = LinkedHashMap::new; final BiConsumer<Map<K, V>, T> accumulator = (map, item) -> map.put(keyMapper.apply(item), valueMapper.apply(item)); final BinaryOperator<Map<K, V>> combiner = (acc1, acc2) -> { acc1.putAll(acc2); return acc1; };
return Collector.of(supplier, accumulator, combiner, finisher); } public static <R, K, V> Collector<Map.Entry<K, V>, ?, R> collectUsingMapAccumulator(@NonNull final Function<Map<K, V>, R> finisher) { return collectUsingMapAccumulator(Map.Entry::getKey, Map.Entry::getValue, finisher); } public static <T> Collector<T, ?, Optional<ImmutableSet<T>>> toOptionalImmutableSet() { return Collectors.collectingAndThen( ImmutableSet.toImmutableSet(), set -> !set.isEmpty() ? Optional.of(set) : Optional.empty()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\GuavaCollectors.java
1
请完成以下Java代码
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { issueSuccessRedirect(request, response); //we handled the success redirect directly, prevent the chain from continuing: return false; } protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception { WebUtils.issueRedirect(request, response, "/", null, true); } // 验证码校验 protected void doCaptchaValidate(HttpServletRequest request, CaptchaUsernamePasswordToken token) { _logger.info("KaptchaFilter.doCaptchaValidate"); //session中的图形码字符串 String captcha = (String) request.getSession().getAttribute( com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); _logger.info("session中的图形码字符串:" + captcha); //比对 if (captcha == null || !captcha.equalsIgnoreCase(token.getCaptcha())) { throw new IncorrectCaptchaException(); } } @Override protected CaptchaUsernamePasswordToken createToken(ServletRequest request, ServletResponse response) { String username = getUsername(request);
String password = getPassword(request); String captcha = getCaptcha(request); boolean rememberMe = isRememberMe(request); String host = getHost(request); return new CaptchaUsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha); } public String getCaptchaParam() { return captchaParam; } public void setCaptchaParam(String captchaParam) { this.captchaParam = captchaParam; } protected String getCaptcha(ServletRequest request) { return WebUtils.getCleanParam(request, getCaptchaParam()); } //保存异常对象到request @Override protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) { request.setAttribute(getFailureKeyAttribute(), ae); } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\shiro\KaptchaFilter.java
1
请完成以下Java代码
public class UserDto implements User, Serializable { private static final long serialVersionUID = 1L; protected final String id; protected String password; protected final String firstName; protected final String lastName; protected final String displayName; protected final String email; protected final String tenantId; protected UserDto(String id, String password, String firstName, String lastName, String displayName, String email, String tenantId) { this.id = id; this.password = password; this.firstName = firstName; this.lastName = lastName; this.displayName = displayName; this.email = email; this.tenantId = tenantId; } @Override public String getId() { return id; } @Override public void setId(String id) { // Not supported } @Override public String getFirstName() { return firstName; } @Override public void setFirstName(String firstName) { // Not supported } @Override public String getLastName() { return lastName; } @Override public void setLastName(String lastName) { // Not supported }
@Override public String getDisplayName() { return displayName; } @Override public void setDisplayName(String displayName) { // Not supported } @Override public String getEmail() { return email; } @Override public void setEmail(String email) { // Not supported } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { // Not supported } @Override public boolean isPictureSet() { return false; } public static UserDto create(User user) { return new UserDto(user.getId(), user.getPassword(), user.getFirstName(), user.getLastName(), user.getDisplayName(), user.getEmail(), user.getTenantId()); } }
repos\flowable-engine-main\modules\flowable-spring-security\src\main\java\org\flowable\spring\security\UserDto.java
1
请完成以下Java代码
public void setAD_BusinessRule_ID (final int AD_BusinessRule_ID) { if (AD_BusinessRule_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_ID, AD_BusinessRule_ID); } @Override public int getAD_BusinessRule_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_ID); } @Override public void setAD_BusinessRule_Precondition_ID (final int AD_BusinessRule_Precondition_ID) { if (AD_BusinessRule_Precondition_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Precondition_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Precondition_ID, AD_BusinessRule_Precondition_ID); } @Override public int getAD_BusinessRule_Precondition_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Precondition_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public org.compiere.model.I_AD_Val_Rule getPrecondition_Rule() { return get_ValueAsPO(COLUMNNAME_Precondition_Rule_ID, org.compiere.model.I_AD_Val_Rule.class); } @Override public void setPrecondition_Rule(final org.compiere.model.I_AD_Val_Rule Precondition_Rule) { set_ValueFromPO(COLUMNNAME_Precondition_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, Precondition_Rule); } @Override public void setPrecondition_Rule_ID (final int Precondition_Rule_ID) { if (Precondition_Rule_ID < 1) set_Value (COLUMNNAME_Precondition_Rule_ID, null);
else set_Value (COLUMNNAME_Precondition_Rule_ID, Precondition_Rule_ID); } @Override public int getPrecondition_Rule_ID() { return get_ValueAsInt(COLUMNNAME_Precondition_Rule_ID); } @Override public void setPreconditionSQL (final @Nullable java.lang.String PreconditionSQL) { set_Value (COLUMNNAME_PreconditionSQL, PreconditionSQL); } @Override public java.lang.String getPreconditionSQL() { return get_ValueAsString(COLUMNNAME_PreconditionSQL); } /** * PreconditionType AD_Reference_ID=541912 * Reference name: PreconditionType */ public static final int PRECONDITIONTYPE_AD_Reference_ID=541912; /** SQL = S */ public static final String PRECONDITIONTYPE_SQL = "S"; /** Validation Rule = R */ public static final String PRECONDITIONTYPE_ValidationRule = "R"; @Override public void setPreconditionType (final java.lang.String PreconditionType) { set_Value (COLUMNNAME_PreconditionType, PreconditionType); } @Override public java.lang.String getPreconditionType() { return get_ValueAsString(COLUMNNAME_PreconditionType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Precondition.java
1
请完成以下Java代码
public CamundaFormDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { Map<String, Object> parameters = new HashMap<>(); parameters.put("deploymentId", deploymentId); parameters.put("camundaFormDefinitionKey", definitionKey); return (CamundaFormDefinitionEntity) getDbEntityManager().selectOne("selectCamundaFormDefinitionByDeploymentAndKey", parameters); } @SuppressWarnings("unchecked") public List<CamundaFormDefinitionEntity> findDefinitionsByDeploymentId(String deploymentId) { return getDbEntityManager().selectList("selectCamundaFormDefinitionByDeploymentId", deploymentId); } @Override public CamundaFormDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) { return getDbEntityManager().getCachedEntity(CamundaFormDefinitionEntity.class, definitionId); }
@Override public CamundaFormDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { throw new UnsupportedOperationException( "Currently finding Camunda Form definition by version tag and tenant is not implemented."); } public void deleteCamundaFormDefinitionsByDeploymentId(String deploymentId) { getDbEntityManager().delete(CamundaFormDefinitionEntity.class, "deleteCamundaFormDefinitionsByDeploymentId", deploymentId); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\entity\CamundaFormDefinitionManager.java
1
请完成以下Java代码
public class CycleBusinessCalendar implements BusinessCalendar { private final static EngineUtilLogger LOG = ProcessEngineLogger.UTIL_LOGGER; public static String NAME = "cycle"; public Date resolveDuedate(String duedateDescription, Task task) { return resolveDuedate(duedateDescription); } public Date resolveDuedate(String duedateDescription) { return resolveDuedate(duedateDescription, (Date)null); } public Date resolveDuedate(String duedateDescription, Date startDate) { return resolveDuedate(duedateDescription, startDate, 0L); } public Date resolveDuedate(String duedateDescription, Date startDate, long repeatOffset) {
try { if (duedateDescription.startsWith("R")) { DurationHelper durationHelper = new DurationHelper(duedateDescription, startDate); durationHelper.setRepeatOffset(repeatOffset); return durationHelper.getDateAfter(startDate); } else { CronTimer cronTimer = CronTimer.parse(duedateDescription); return cronTimer.getDueDate(startDate == null ? ClockUtil.getCurrentTime() : startDate); } } catch (Exception e) { throw LOG.exceptionWhileParsingCycleExpresison(duedateDescription, e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\calendar\CycleBusinessCalendar.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_CM_ChatTypeUpdate[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_User getAD_User() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getAD_User_ID(), get_TrxName()); } /** Set User/Contact. @param AD_User_ID User within the system - Internal or Business Partner Contact */ public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get User/Contact. @return User within the system - Internal or Business Partner Contact */ public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_ChatType getCM_ChatType() throws RuntimeException { return (I_CM_ChatType)MTable.get(getCtx(), I_CM_ChatType.Table_Name) .getPO(getCM_ChatType_ID(), get_TrxName()); } /** Set Chat Type. @param CM_ChatType_ID Type of discussion / chat */ public void setCM_ChatType_ID (int CM_ChatType_ID) { if (CM_ChatType_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null); else
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID)); } /** Get Chat Type. @return Type of discussion / chat */ public int getCM_ChatType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Self-Service. @param IsSelfService This is a Self-Service entry or this entry can be changed via Self-Service */ public void setIsSelfService (boolean IsSelfService) { set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService)); } /** Get Self-Service. @return This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatTypeUpdate.java
1
请在Spring Boot框架中完成以下Java代码
static class ThymeleafWebFluxConfiguration { @Bean @ConditionalOnMissingBean(name = "thymeleafReactiveViewResolver") ThymeleafReactiveViewResolver thymeleafViewResolver(ISpringWebFluxTemplateEngine templateEngine, ThymeleafProperties properties) { ThymeleafReactiveViewResolver resolver = new ThymeleafReactiveViewResolver(); resolver.setTemplateEngine(templateEngine); mapProperties(properties, resolver); mapReactiveProperties(properties.getReactive(), resolver); // This resolver acts as a fallback resolver (e.g. like a // InternalResourceViewResolver) so it needs to have low precedence resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5); return resolver; } private void mapProperties(ThymeleafProperties properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getEncoding).to(resolver::setDefaultCharset); resolver.setExcludedViewNames(properties.getExcludedViewNames()); resolver.setViewNames(properties.getViewNames()); } private void mapReactiveProperties(Reactive properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getMediaTypes).to(resolver::setSupportedMediaTypes); map.from(properties::getMaxChunkSize) .asInt(DataSize::toBytes) .when((size) -> size > 0) .to(resolver::setResponseMaxChunkSizeBytes); map.from(properties::getFullModeViewNames).to(resolver::setFullModeViewNames); map.from(properties::getChunkedModeViewNames).to(resolver::setChunkedModeViewNames); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LayoutDialect.class) static class ThymeleafWebLayoutConfiguration {
@Bean @ConditionalOnMissingBean LayoutDialect layoutDialect() { return new LayoutDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(DataAttributeDialect.class) static class DataAttributeDialectConfiguration { @Bean @ConditionalOnMissingBean DataAttributeDialect dialect() { return new DataAttributeDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ SpringSecurityDialect.class, CsrfToken.class }) static class ThymeleafSecurityDialectConfiguration { @Bean @ConditionalOnMissingBean SpringSecurityDialect securityDialect() { return new SpringSecurityDialect(); } } }
repos\spring-boot-4.0.1\module\spring-boot-thymeleaf\src\main\java\org\springframework\boot\thymeleaf\autoconfigure\ThymeleafAutoConfiguration.java
2
请完成以下Java代码
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(EVENTBUS_TOPIC); } private AdMessageKey getNotificationAD_Message(final I_M_InOut inout) { final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inout.getDocStatus()); if (docStatus.isReversedOrVoided()) { return inout.isSOTrx() ? MSG_Event_ShipmentReversed : MSG_Event_ReceiptReversed; } else { return inout.isSOTrx() ? MSG_Event_ShipmentGenerated : MSG_Event_ReceiptGenerated; } } private UserId getNotificationRecipientUserId(final I_M_InOut inout) { // // In case of reversal i think we shall notify the current user too final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inout.getDocStatus()); if (docStatus.isReversedOrVoided()) { final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user if (currentUserId > 0) { return UserId.ofRepoId(currentUserId); } return UserId.ofRepoId(inout.getUpdatedBy()); // last updated }
// // Fallback: notify only the creator else { return UserId.ofRepoId(inout.getCreatedBy()); } } public InOutUserNotificationsProducer notifyShipmentError( @NonNull final String sourceInfo, @NonNull final String errorMessage) { // don't send after commit, because the trx will very probably be rolled back if an error happened notificationBL.send(newUserNotificationRequest() .recipientUserId(Env.getLoggedUserId()) .contentADMessage(MSG_Event_ShipmentError) .contentADMessageParam(sourceInfo) .contentADMessageParam(errorMessage) .build()); return this; } private void postNotifications(final List<UserNotificationRequest> notifications) { notificationBL.sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\event\InOutUserNotificationsProducer.java
1
请在Spring Boot框架中完成以下Java代码
public int size() { return joinColumns.size(); } @Override public Iterator<FTSJoinColumn> iterator() { return joinColumns.iterator(); } public String buildJoinCondition( @NonNull final String targetTableNameOrAlias, @Nullable final String selectionTableNameOrAlias) { Check.assumeNotEmpty(targetTableNameOrAlias, "targetTableNameOrAlias not empty"); final String selectionTableNameOrAliasWithDot = StringUtils.trimBlankToOptional(selectionTableNameOrAlias) .map(alias -> alias + ".") .orElse(""); final StringBuilder sql = new StringBuilder(); for (final FTSJoinColumn joinColumn : joinColumns) { if (sql.length() > 0) { sql.append(" AND "); } if (joinColumn.isNullable()) { sql.append("(") .append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName()).append(" IS NULL") .append(" OR ")
.append(targetTableNameOrAlias).append(".").append(joinColumn.getTargetTableColumnName()) .append(" IS NOT DISTINCT FROM ") .append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName()) .append(")"); } else { sql.append(targetTableNameOrAlias).append(".").append(joinColumn.getTargetTableColumnName()) .append("=") .append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName()); } } return sql.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSJoinColumnList.java
2
请完成以下Java代码
public String getBookList(ModelMap map) { map.addAttribute("bookList",bookService.findAll()); return BOOK_LIST_PATH_NAME; } /** * 获取创建 Book 表单 */ @RequestMapping(value = "/create", method = RequestMethod.GET) public String createBookForm(ModelMap map) { map.addAttribute("book", new Book()); map.addAttribute("action", "create"); return BOOK_FORM_PATH_NAME; } /** * 创建 Book * 处理 "/book/create" 的 POST 请求,用来新建 Book 信息 * 通过 @ModelAttribute 绑定表单实体参数,也通过 @RequestParam 传递参数 */ @RequestMapping(value = "/create", method = RequestMethod.POST) public String postBook(@ModelAttribute Book book) { bookService.insertByBook(book); return REDIRECT_TO_BOOK_URL; } /** * 获取更新 Book 表单 * 处理 "/book/update/{id}" 的 GET 请求,通过 URL 中的 id 值获取 Book 信息 * URL 中的 id ,通过 @PathVariable 绑定参数
*/ @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String getUser(@PathVariable Long id, ModelMap map) { map.addAttribute("book", bookService.findById(id)); map.addAttribute("action", "update"); return BOOK_FORM_PATH_NAME; } /** * 更新 Book * 处理 "/update" 的 PUT 请求,用来更新 Book 信息 */ @RequestMapping(value = "/update", method = RequestMethod.POST) public String putBook(@ModelAttribute Book book) { bookService.update(book); return REDIRECT_TO_BOOK_URL; } /** * 删除 Book * 处理 "/book/{id}" 的 GET 请求,用来删除 Book 信息 */ @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) public String deleteBook(@PathVariable Long id) { bookService.delete(id); return REDIRECT_TO_BOOK_URL; } }
repos\springboot-learning-example-master\chapter-5-spring-boot-data-jpa\src\main\java\demo\springboot\web\BookController.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getYoutubeChannel() { return youtubeChannel; } public void setYoutubeChannel(String youtubeChannel) { this.youtubeChannel = youtubeChannel; } public String getHobby() { return hobby;
} public void setHobby(String hobby) { this.hobby = hobby; } @Override public String toString() { return "InstructorDetail [id=" + id + ", youtubeChannel=" + youtubeChannel + ", hobby=" + hobby + "]"; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-jpa-one-to-one-example\src\main\java\net\alanbinu\springboot\jpa\model\InstructorDetail.java
1
请完成以下Java代码
public int getC_CompensationGroup_Schema_TemplateLine_ID() { return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_TemplateLine_ID); } @Override public void setC_Flatrate_Conditions_ID (final int C_Flatrate_Conditions_ID) { if (C_Flatrate_Conditions_ID < 1) set_Value (COLUMNNAME_C_Flatrate_Conditions_ID, null); else set_Value (COLUMNNAME_C_Flatrate_Conditions_ID, C_Flatrate_Conditions_ID); } @Override public int getC_Flatrate_Conditions_ID() { return get_ValueAsInt(COLUMNNAME_C_Flatrate_Conditions_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setIsAllowSeparateInvoicing (final boolean IsAllowSeparateInvoicing) { set_Value (COLUMNNAME_IsAllowSeparateInvoicing, IsAllowSeparateInvoicing); } @Override public boolean isAllowSeparateInvoicing() { return get_ValueAsBoolean(COLUMNNAME_IsAllowSeparateInvoicing); } @Override public void setIsHideWhenPrinting (final boolean IsHideWhenPrinting) { set_Value (COLUMNNAME_IsHideWhenPrinting, IsHideWhenPrinting); }
@Override public boolean isHideWhenPrinting() { return get_ValueAsBoolean(COLUMNNAME_IsHideWhenPrinting); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_Schema_TemplateLine.java
1
请完成以下Java代码
public int vote(Authentication authentication, MethodInvocation object, Collection<ConfigAttribute> attributes) { for (ConfigAttribute attr : attributes) { if (!supports(attr)) { continue; } // Need to make an access decision on this invocation // Attempt to locate the domain object instance to process Object domainObject = getDomainObjectInstance(object); // If domain object is null, vote to abstain if (domainObject == null) { logger.debug("Voting to abstain - domainObject is null"); return ACCESS_ABSTAIN; } // Evaluate if we are required to use an inner domain object if (StringUtils.hasText(this.internalMethod)) { domainObject = invokeInternalMethod(domainObject); } // Obtain the OID applicable to the domain object ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); // Obtain the SIDs applicable to the principal List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication); Acl acl; try { // Lookup only ACLs for SIDs we're interested in acl = this.aclService.readAclById(objectIdentity, sids); } catch (NotFoundException ex) { logger.debug("Voting to deny access - no ACLs apply for this principal"); return ACCESS_DENIED; } try { if (acl.isGranted(this.requirePermission, sids, false)) { logger.debug("Voting to grant access"); return ACCESS_GRANTED; } logger.debug("Voting to deny access - ACLs returned, but insufficient permissions for this principal"); return ACCESS_DENIED; } catch (NotFoundException ex) {
logger.debug("Voting to deny access - no ACLs apply for this principal"); return ACCESS_DENIED; } } // No configuration attribute matched, so abstain return ACCESS_ABSTAIN; } private Object invokeInternalMethod(Object domainObject) { try { Class<?> domainObjectType = domainObject.getClass(); Method method = domainObjectType.getMethod(this.internalMethod, new Class[0]); return method.invoke(domainObject); } catch (NoSuchMethodException ex) { throw new AuthorizationServiceException("Object of class '" + domainObject.getClass() + "' does not provide the requested internalMethod: " + this.internalMethod); } catch (IllegalAccessException ex) { logger.debug("IllegalAccessException", ex); throw new AuthorizationServiceException( "Problem invoking internalMethod: " + this.internalMethod + " for object: " + domainObject); } catch (InvocationTargetException ex) { logger.debug("InvocationTargetException", ex); throw new AuthorizationServiceException( "Problem invoking internalMethod: " + this.internalMethod + " for object: " + domainObject); } } }
repos\spring-security-main\access\src\main\java\org\springframework\security\acls\AclEntryVoter.java
1
请完成以下Java代码
private void lock2(User a, User b) { while (true) { try { if (a.getLock().tryLock()) { try { if (b.getLock().tryLock()) { System.out.println(Thread.currentThread().getName() + " 死锁示例"); break; } } finally { b.getLock().unlock(); } } } finally { a.getLock().unlock(); } // 拿锁失败以后,休眠随机数,以避免活锁 sleep(random.nextInt()); } } private void deadlock(User a, User b) { synchronized (a) { sleep(1000); synchronized (b) { sleep(1000); System.out.println(Thread.currentThread().getName() + " 死锁示例");
} } } public static void sleep(int probe) { try { Thread.sleep(probe); } catch (InterruptedException e) { e.printStackTrace(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\LockTest.java
1
请完成以下Java代码
public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID) { if (M_AttributeSetExclude_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID)); } /** Get Exclude Attribute Set. @return Exclude the ability to enter Attribute Sets */ public int getM_AttributeSetExclude_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_AttributeSet getM_AttributeSet() throws RuntimeException { return (I_M_AttributeSet)MTable.get(getCtx(), I_M_AttributeSet.Table_Name) .getPO(getM_AttributeSet_ID(), get_TrxName()); } /** Set Attribute Set. @param M_AttributeSet_ID Product Attribute Set */ public void setM_AttributeSet_ID (int M_AttributeSet_ID) { if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID)); } /** Get Attribute Set. @return Product Attribute Set */ public int getM_AttributeSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetExclude.java
1
请完成以下Java代码
public CmmnClassDelegate createLifeCycleListener(String className, String sourceState, String targetState, List<FieldExtension> fieldExtensions) { CmmnClassDelegate cmmnClassDelegate = create(className, fieldExtensions); cmmnClassDelegate.setSourceState(sourceState); cmmnClassDelegate.setTargetState(targetState); return cmmnClassDelegate; } @Override public Object defaultInstantiateDelegate(Class<?> clazz, ServiceTask serviceTask, boolean allExpressions) { Object object = ReflectUtil.instantiate(clazz.getName()); if (serviceTask != null) { for (FieldExtension extension : serviceTask.getFieldExtensions()) { Object value; if (StringUtils.isNotEmpty(extension.getExpression())) { value = expressionManager.createExpression(extension.getExpression());
} else if (allExpressions) { value = new FixedValue(extension.getStringValue()); } else { value = extension.getStringValue(); } ReflectUtil.invokeSetterOrField(object, extension.getFieldName(), value, false); } ReflectUtil.invokeSetterOrField(object, "serviceTask", serviceTask, false); } return object; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\DefaultCmmnClassDelegateFactory.java
1
请完成以下Java代码
public class Link { private final String href; private final boolean templated; /** * Creates a new {@link Link} with the given {@code href}. * @param href the href */ public Link(String href) { Assert.notNull(href, "'href' must not be null"); this.href = href; this.templated = href.contains("{"); } /** * Returns the href of the link. * @return the href */ public String getHref() { return this.href; }
/** * Returns whether the {@link #getHref() href} is templated. * @return {@code true} if the href is templated, otherwise {@code false} */ public boolean isTemplated() { return this.templated; } @Override public String toString() { return new ToStringCreator(this).append("href", this.href).toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\Link.java
1
请完成以下Java代码
public void setQtyReserved (final BigDecimal QtyReserved) { set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyScrap (final BigDecimal QtyScrap) { set_ValueNoCheck (COLUMNNAME_QtyScrap, QtyScrap); } @Override public BigDecimal getQtyScrap() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyScrap); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyUsageVariance (final BigDecimal QtyUsageVariance) { set_Value (COLUMNNAME_QtyUsageVariance, QtyUsageVariance); } @Override public BigDecimal getQtyUsageVariance() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyUsageVariance); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setScrap (final @Nullable BigDecimal Scrap) { set_ValueNoCheck (COLUMNNAME_Scrap, Scrap); } @Override public BigDecimal getScrap() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Scrap); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setShowSubBOMIngredients (final boolean ShowSubBOMIngredients) { set_Value (COLUMNNAME_ShowSubBOMIngredients, ShowSubBOMIngredients); } @Override public boolean isShowSubBOMIngredients() { return get_ValueAsBoolean(COLUMNNAME_ShowSubBOMIngredients); } @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); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); }
@Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } /** * VariantGroup AD_Reference_ID=540490 * Reference name: VariantGroup */ public static final int VARIANTGROUP_AD_Reference_ID=540490; /** 01 = 01 */ public static final String VARIANTGROUP_01 = "01"; /** 02 = 02 */ public static final String VARIANTGROUP_02 = "02"; /** 03 = 03 */ public static final String VARIANTGROUP_03 = "03"; /** 04 = 04 */ public static final String VARIANTGROUP_04 = "04"; /** 05 = 05 */ public static final String VARIANTGROUP_05 = "05"; /** 06 = 06 */ public static final String VARIANTGROUP_06 = "06"; /** 07 = 07 */ public static final String VARIANTGROUP_07 = "07"; /** 08 = 08 */ public static final String VARIANTGROUP_08 = "08"; /** 09 = 09 */ public static final String VARIANTGROUP_09 = "09"; @Override public void setVariantGroup (final @Nullable java.lang.String VariantGroup) { set_Value (COLUMNNAME_VariantGroup, VariantGroup); } @Override public java.lang.String getVariantGroup() { return get_ValueAsString(COLUMNNAME_VariantGroup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOMLine.java
1
请完成以下Java代码
public int getAD_Tree_ID(final PO po) { if (!InterfaceWrapperHelper.isInstanceOf(po, I_C_ElementValue.class)) { return -1; } final I_C_ElementValue ev = InterfaceWrapperHelper.create(po, I_C_ElementValue.class); final ChartOfAccountsId chartOfAccountsId = ChartOfAccountsId.ofRepoId(ev.getC_Element_ID()); final AdTreeId chartOfAccountsTreeId = chartOfAccountsService().getById(chartOfAccountsId).getTreeId(); return chartOfAccountsTreeId.getRepoId(); } private ChartOfAccountsService chartOfAccountsService() { ChartOfAccountsService chartOfAccountsService = this._chartOfAccountsService; if (chartOfAccountsService == null) { chartOfAccountsService = this._chartOfAccountsService = SpringContextHolder.instance.getBean(ChartOfAccountsService.class); } return chartOfAccountsService; } @Override public String getWhereClause(final MTree_Base tree) {
final ChartOfAccountsId chartOfAccountsId = getChartOfAccountsId(tree).orElse(null); if (chartOfAccountsId == null) { // the tree is not yet referenced from any C_Element record. maybe it was just created return "0=1"; } else { return I_C_ElementValue.COLUMNNAME_C_Element_ID + "=" + chartOfAccountsId.getRepoId(); } } private Optional<ChartOfAccountsId> getChartOfAccountsId(final MTree_Base tree) { return chartOfAccountsService() .getByTreeId(AdTreeId.ofRepoId(tree.getAD_Tree_ID())) .map(ChartOfAccounts::getId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\MElementValueTreeSupport.java
1
请完成以下Java代码
public List<File> getFiles() { return this.files; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } DockerComposeFile other = (DockerComposeFile) obj; return this.files.equals(other.files); } @Override public int hashCode() { return this.files.hashCode(); } @Override public String toString() { if (this.files.size() == 1) { return this.files.get(0).getPath(); } return this.files.stream().map(File::toString).collect(Collectors.joining(", ")); } /** * Find the Docker Compose file by searching in the given working directory. Files are * considered in the same order that {@code docker compose} uses, namely: * <ul> * <li>{@code compose.yaml}</li> * <li>{@code compose.yml}</li> * <li>{@code docker-compose.yaml}</li> * <li>{@code docker-compose.yml}</li> * </ul> * @param workingDirectory the working directory to search or {@code null} to use the * current directory * @return the located file or {@code null} if no Docker Compose file can be found */ public static @Nullable DockerComposeFile find(@Nullable File workingDirectory) { File base = (workingDirectory != null) ? workingDirectory : new File("."); if (!base.exists()) { return null; }
Assert.state(base.isDirectory(), () -> "'%s' is not a directory".formatted(base)); Path basePath = base.toPath(); for (String candidate : SEARCH_ORDER) { Path resolved = basePath.resolve(candidate); if (Files.exists(resolved)) { return of(resolved.toAbsolutePath().toFile()); } } return null; } /** * Create a new {@link DockerComposeFile} for the given {@link File}. * @param file the source file * @return the Docker Compose file */ public static DockerComposeFile of(File file) { Assert.notNull(file, "'file' must not be null"); Assert.isTrue(file.exists(), () -> "'file' [%s] must exist".formatted(file)); Assert.isTrue(file.isFile(), () -> "'file' [%s] must be a normal file".formatted(file)); return new DockerComposeFile(Collections.singletonList(file)); } /** * Creates a new {@link DockerComposeFile} for the given {@link File files}. * @param files the source files * @return the Docker Compose file * @since 3.4.0 */ public static DockerComposeFile of(Collection<? extends File> files) { Assert.notNull(files, "'files' must not be null"); for (File file : files) { Assert.notNull(file, "'files' must not contain null elements"); Assert.isTrue(file.exists(), () -> "'files' content [%s] must exist".formatted(file)); Assert.isTrue(file.isFile(), () -> "'files' content [%s] must be a normal file".formatted(file)); } return new DockerComposeFile(List.copyOf(files)); } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DockerComposeFile.java
1
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get User/Contact. @return User within the system - Internal or Business Partner Contact */ public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) {
set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Buyer.java
1
请在Spring Boot框架中完成以下Java代码
public class RabbitMQConfig { public static final String QUEUENAME_MSV3ServerRequests = "msv3-server-requests"; public static final String QUEUENAME_UserChangedEvents = "msv3-server-UserChangedEvents"; public static final String QUEUENAME_StockAvailabilityUpdatedEvent = "msv3-server-StockAvailabilityUpdatedEvents"; public static final String QUEUENAME_ProductExcludeUpdatedEvents = "msv3-server-ProductExcludeUpdatedEvents"; public static final String QUEUENAME_SyncOrderRequestEvents = "msv3-server-SyncOrderRequestEvents"; public static final String QUEUENAME_SyncOrderResponseEvents = "msv3-server-SyncOrderResponseEvents"; @Bean(name = QUEUENAME_MSV3ServerRequests) public Queue msv3ServerRequestsQueue() { return new Queue(QUEUENAME_MSV3ServerRequests); } @Bean(name = QUEUENAME_UserChangedEvents) public Queue userChangedEventsQueue() { return new Queue(QUEUENAME_UserChangedEvents); } @Bean(name = QUEUENAME_StockAvailabilityUpdatedEvent) public Queue stockAvailabilityUpdatedEventQueue() { return new Queue(QUEUENAME_StockAvailabilityUpdatedEvent); } @Bean(name = QUEUENAME_ProductExcludeUpdatedEvents) public Queue productExcludeUpdatedEventsQueue() { return new Queue(QUEUENAME_ProductExcludeUpdatedEvents); } @Bean(name = QUEUENAME_SyncOrderRequestEvents) public Queue syncOrderRequestEventsQueue() { return new Queue(QUEUENAME_SyncOrderRequestEvents); }
@Bean(name = QUEUENAME_SyncOrderResponseEvents) public Queue syncOrderResponseEventsQueue() { return new Queue(QUEUENAME_SyncOrderResponseEvents); } // Note: with spring boot-2 this somehow didn't work anymore. It didn't create the queues in rabbitmq, so i added the code above, which works. // @Bean // List<Declarable> queuesAndBindings() // { // return ImmutableList.<Declarable> builder() // .addAll(createQueueExchangeAndBinding(QUEUENAME_MSV3ServerRequests)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_UserChangedEvents)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_StockAvailabilityUpdatedEvent)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_ProductExcludeUpdatedEvents)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_SyncOrderRequestEvents)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_SyncOrderResponseEvents)) // .build(); // } // private static List<Declarable> createQueueExchangeAndBinding(final String queueName) // { // final Queue queue = QueueBuilder.nonDurable(queueName).build(); // final TopicExchange exchange = new TopicExchange(queueName + "-exchange"); // final Binding binding = BindingBuilder.bind(queue).to(exchange).with(queueName); // return ImmutableList.<Declarable> of(queue, exchange, binding); // } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\RabbitMQConfig.java
2
请完成以下Spring Boot application配置
feature.foo.by.id=Y feature.new.foo=Y last.active.after=2018-03-14T00:00:00Z first.active.after=2999-03-15T00:00:00Z logging.level.org.flips=info #actuator properties ### server port server.port=8080 #port used to expose actuator management.port=8081 #CIDR allowed to hit actuator management.address=127.0.0.1 # Actuator Configuration # customize /beans endpoint endpoints.beans.id=springbeans endpoints.beans.sensitive=false endpoints.beans.enabled=true # for the Spring Boot version 1.5.0 and above, we have to disable security to expose the health endpoint fully for unauthorized access. # see: https://docs.spring.io/spring-boot/doc
s/1.5.x/reference/html/production-ready-monitoring.html management.security.enabled=false endpoints.health.sensitive=false # customize /info endpoint info.app.name=Spring Sample Application info.app.description=This is my first spring boot application info.app.version=1.0.0
repos\tutorials-master\spring-4\src\main\resources\application.properties
2
请完成以下Java代码
public VariableInstanceEntity findVariableInstanceByExecutionAndName(String executionId, String variableName) { Map<String, String> params = new HashMap<String, String>(2); params.put("executionId", executionId); params.put("name", variableName); return (VariableInstanceEntity) getDbSqlSession().selectOne("selectVariableInstanceByExecutionAndName", params); } @Override @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByExecutionAndNames( String executionId, Collection<String> names ) { Map<String, Object> params = new HashMap<String, Object>(2); params.put("executionId", executionId); params.put("names", names); return getDbSqlSession().selectList("selectVariableInstancesByExecutionAndNames", params); }
@Override public VariableInstanceEntity findVariableInstanceByTaskAndName(String taskId, String variableName) { Map<String, String> params = new HashMap<String, String>(2); params.put("taskId", taskId); params.put("name", variableName); return (VariableInstanceEntity) getDbSqlSession().selectOne("selectVariableInstanceByTaskAndName", params); } @Override @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByTaskAndNames(String taskId, Collection<String> names) { Map<String, Object> params = new HashMap<String, Object>(2); params.put("taskId", taskId); params.put("names", names); return getDbSqlSession().selectList("selectVariableInstancesByTaskAndNames", params); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisVariableInstanceDataManager.java
1
请完成以下Java代码
public Map<String, TransitionImpl> getSequenceFlows() { return sequenceFlows; } public ProcessDefinitionEntity getCurrentProcessDefinition() { return currentProcessDefinition; } public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) { this.currentProcessDefinition = currentProcessDefinition; } public FlowElement getCurrentFlowElement() { return currentFlowElement; } public void setCurrentFlowElement(FlowElement currentFlowElement) { this.currentFlowElement = currentFlowElement; } public ActivityImpl getCurrentActivity() { return currentActivity; } public void setCurrentActivity(ActivityImpl currentActivity) { this.currentActivity = currentActivity; } public void setCurrentSubProcess(SubProcess subProcess) { currentSubprocessStack.push(subProcess); } public SubProcess getCurrentSubProcess() { return currentSubprocessStack.peek(); }
public void removeCurrentSubProcess() { currentSubprocessStack.pop(); } public void setCurrentScope(ScopeImpl scope) { currentScopeStack.push(scope); } public ScopeImpl getCurrentScope() { return currentScopeStack.peek(); } public void removeCurrentScope() { currentScopeStack.pop(); } public BpmnParse setSourceSystemId(String systemId) { sourceSystemId = systemId; return this; } public String getSourceSystemId() { return this.sourceSystemId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java
1
请完成以下Java代码
public T sql(String sqlStatement) { this.sqlStatement = sqlStatement; return (T) this; } @SuppressWarnings("unchecked") @Override public T parameter(String name, Object value) { parameters.put(name, value); return (T) this; } protected Map<String, Object> generateParameterMap() { Map<String, Object> parameterMap = new HashMap<>(parameters); parameterMap.put("sql", sqlStatement); parameterMap.put("resultType", resultType.toString()); parameterMap.put("firstResult", firstResult); parameterMap.put("maxResults", maxResults); parameterMap.put("needsPaging", firstResult >= 0); String orderBy = (String) parameterMap.get("orderBy"); if (orderBy != null && !"".equals(orderBy)) { orderBy = "RES." + orderBy; } else {
orderBy = "RES.ID_ asc"; } parameterMap.put("orderBy", "order by " + orderBy); parameterMap.put("orderByForWindow", "order by " + orderBy); parameterMap.put("orderByColumns", orderBy); int firstRow = firstResult + 1; parameterMap.put("firstRow", firstRow); int lastRow = 0; if (maxResults == Integer.MAX_VALUE) { lastRow = maxResults; } else { lastRow = firstResult + maxResults + 1; } parameterMap.put("lastRow", lastRow); return parameterMap; } public Map<String, Object> getParameters() { return parameters; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\query\BaseNativeQuery.java
1
请完成以下Java代码
class QuizGeneratorAgent { private final Resource promptTemplate; QuizGeneratorAgent(@Value("classpath:prompt-templates/quiz-generation.txt") Resource promptTemplate) { this.promptTemplate = promptTemplate; } @Action(toolGroups = CoreToolGroups.WEB) Blog fetchBlogContent(UserInput userInput) { return PromptRunner .usingLlm() .createObject( "Fetch the blog content from the URL given in the following request: '%s'".formatted(userInput), Blog.class ); }
@Action @AchievesGoal(description = "Quiz has been generated") Quiz generateQuiz(Blog blog) throws IOException { String prompt = promptTemplate .getContentAsString(Charset.defaultCharset()) .formatted( blog.getTitle(), blog.getContent() ); return PromptRunner .usingLlm() .createObject( prompt, Quiz.class ); } }
repos\tutorials-master\embabel-modules\embabel-quiz-generator\src\main\java\com\baeldung\quizzard\QuizGeneratorAgent.java
1
请完成以下Java代码
public boolean isExtended() { return extensionId != null && !extensionId.isEmpty(); } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public boolean isUseLocalScopeForResultVariable() { return useLocalScopeForResultVariable; } public void setUseLocalScopeForResultVariable(boolean useLocalScopeForResultVariable) { this.useLocalScopeForResultVariable = useLocalScopeForResultVariable; } public boolean isTriggerable() { return triggerable; } public void setTriggerable(boolean triggerable) { this.triggerable = triggerable; } public boolean isStoreResultVariableAsTransient() { return storeResultVariableAsTransient; } public void setStoreResultVariableAsTransient(boolean storeResultVariableAsTransient) { this.storeResultVariableAsTransient = storeResultVariableAsTransient; } @Override public ServiceTask clone() { ServiceTask clone = new ServiceTask(); clone.setValues(this); return clone; }
public void setValues(ServiceTask otherElement) { super.setValues(otherElement); setImplementation(otherElement.getImplementation()); setImplementationType(otherElement.getImplementationType()); setResultVariableName(otherElement.getResultVariableName()); setType(otherElement.getType()); setOperationRef(otherElement.getOperationRef()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression()); setUseLocalScopeForResultVariable(otherElement.isUseLocalScopeForResultVariable()); setTriggerable(otherElement.isTriggerable()); setStoreResultVariableAsTransient(otherElement.isStoreResultVariableAsTransient()); fieldExtensions = new ArrayList<>(); if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherElement.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } customProperties = new ArrayList<>(); if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) { for (CustomProperty property : otherElement.getCustomProperties()) { customProperties.add(property.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ServiceTask.java
1
请完成以下Java代码
public Object getPrincipal() { return this.clientId; } @Nullable @Override public Object getCredentials() { return this.credentials; } /** * Returns the authenticated {@link RegisteredClient registered client}, or * {@code null} if not authenticated. * @return the authenticated {@link RegisteredClient}, or {@code null} if not * authenticated */ @Nullable public RegisteredClient getRegisteredClient() { return this.registeredClient;
} /** * Returns the {@link ClientAuthenticationMethod authentication method} used by the * client. * @return the {@link ClientAuthenticationMethod} used by the client */ public ClientAuthenticationMethod getClientAuthenticationMethod() { return this.clientAuthenticationMethod; } /** * Returns the additional parameters. * @return the additional parameters */ public Map<String, Object> getAdditionalParameters() { return this.additionalParameters; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2ClientAuthenticationToken.java
1
请完成以下Java代码
private PodTemplateSpec buildPodTemplate(DeptrackResource primary, ObjectMeta primaryMeta) { return new PodTemplateSpecBuilder() .withMetadata(primaryMeta) .withSpec(buildPodSpec(primary)) .build(); } private PodSpec buildPodSpec(DeptrackResource primary) { // Check for version override String imageVersion = StringUtils.hasText(primary.getSpec().getApiServerVersion())? ":" + primary.getSpec().getApiServerVersion().trim():""; // Check for image override String imageName = StringUtils.hasText(primary.getSpec().getApiServerImage())? primary.getSpec().getApiServerImage().trim(): Constants.DEFAULT_API_SERVER_IMAGE; //@formatter:off return new PodSpecBuilder(template.getSpec().getTemplate().getSpec())
.editContainer(0) // Assumes we have a single container .withImage(imageName + imageVersion) .and() .build(); //@formatter:on } static class Discriminator extends ResourceIDMatcherDiscriminator<Deployment,DeptrackResource> { public Discriminator() { super(COMPONENT, (p) -> new ResourceID(p.getMetadata() .getName() + "-" + COMPONENT, p.getMetadata() .getNamespace())); } } }
repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackApiServerDeploymentResource.java
1
请完成以下Java代码
public IAllocationRequestBuilder addEmptyHUListener(@NonNull final EmptyHUListener emptyHUListener) { if (emptyHUListeners == null) { emptyHUListeners = new ArrayList<>(); } emptyHUListeners.add(emptyHUListener); return this; } @Override public IAllocationRequestBuilder setClearanceStatusInfo(@Nullable final ClearanceStatusInfo clearanceStatusInfo) { this.clearanceStatusInfo = clearanceStatusInfo; return this; } @Override @Nullable public ClearanceStatusInfo getClearanceStatusInfo() { if (clearanceStatusInfo != null) { return clearanceStatusInfo; } else if (baseAllocationRequest != null) { return baseAllocationRequest.getClearanceStatusInfo(); } return null; } @Override public IAllocationRequestBuilder setDeleteEmptyAndJustCreatedAggregatedTUs(@Nullable final Boolean deleteEmptyAndJustCreatedAggregatedTUs) { this.deleteEmptyAndJustCreatedAggregatedTUs = deleteEmptyAndJustCreatedAggregatedTUs; return this; } private boolean isDeleteEmptyAndJustCreatedAggregatedTUs() { if (deleteEmptyAndJustCreatedAggregatedTUs != null) { return deleteEmptyAndJustCreatedAggregatedTUs; } else if (baseAllocationRequest != null) {
return baseAllocationRequest.isDeleteEmptyAndJustCreatedAggregatedTUs(); } return false; } @Override public IAllocationRequest create() { final IHUContext huContext = getHUContextToUse(); final ProductId productId = getProductIdToUse(); final Quantity quantity = getQuantityToUse(); final ZonedDateTime date = getDateToUse(); final TableRecordReference fromTableRecord = getFromReferencedTableRecordToUse(); final boolean forceQtyAllocation = isForceQtyAllocationToUse(); final ClearanceStatusInfo clearanceStatusInfo = getClearanceStatusInfo(); return new AllocationRequest( huContext, productId, quantity, date, fromTableRecord, forceQtyAllocation, clearanceStatusInfo, isDeleteEmptyAndJustCreatedAggregatedTUs()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationRequestBuilder.java
1
请完成以下Java代码
public TaxAccounts getTaxAccounts( @NonNull final AcctSchemaId acctSchemaId, @NonNull final TaxId taxId) { return taxAccountsRepository.getAccounts(taxId, acctSchemaId); } @NonNull public Account getProductAccount( @NonNull final AcctSchemaId acctSchemaId, @Nullable final ProductId productId, @Nullable final TaxId taxId, @NonNull final ProductAcctType acctType) { if (extension != null) { final Account account = extension.getProductAccount(acctSchemaId, productId, acctType).orElse(null); if (account != null) { return account; } } // // Product Revenue: check/use the override defined on tax level if (acctType == ProductAcctType.P_Revenue_Acct && taxId != null) { final Account productRevenueAcct = taxAccountsRepository.getAccounts(taxId, acctSchemaId) .getT_Revenue_Acct() .orElse(null); if (productRevenueAcct != null) { return productRevenueAcct; } }
if (productId == null) { return productCategoryAccountsRepository .getAccounts(productBL.getDefaultProductCategoryId(), acctSchemaId) .map(accounts -> accounts.getAccount(acctType)) .orElseThrow(() -> newPostingException().setDetailMessage("No Default Account for account type: " + acctType)); } else { return productAccountsRepository.getAccounts(productId, acctSchemaId).getAccount(acctType); } } public Account getCostElementAccount( @NonNull final AcctSchemaId acctSchemaId, @NonNull final CostElementId costElementId, @NonNull final CostElementAccountType acctType) { final AccountId accountId = costElementAccountsRepository .getAccounts(costElementId, acctSchemaId) .getAccountId(acctType); return Account.of(accountId, acctType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\AccountProvider.java
1
请完成以下Java代码
public ProductionMaterialType getType() { return type; } @Override public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw) { Check.assumeNotNull(qtyDeliveredPercOfRaw, "qtyDeliveredPercOfRaw not null"); this.qtyDeliveredPercOfRaw = qtyDeliveredPercOfRaw; } @Override public BigDecimal getQM_QtyDeliveredPercOfRaw() { return qtyDeliveredPercOfRaw; } @Override public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg) { Check.assumeNotNull(qtyDeliveredAvg, "qtyDeliveredAvg not null"); this.qtyDeliveredAvg = qtyDeliveredAvg; } @Override public BigDecimal getQM_QtyDeliveredAvg() { return qtyDeliveredAvg; } @Override public String getVariantGroup() { return null; }
@Override public BOMComponentType getComponentType() { return null; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { return handlingUnitsInfo; } @Override public I_M_Product getMainComponentProduct() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PlainProductionMaterial.java
1
请完成以下Java代码
public boolean lowerCaseContains() { return src.toLowerCase() .contains(dest.toLowerCase()); } // matches() with Regular Expressions @Benchmark public boolean matchesRegularExpression() { return src.matches("(?i).*" + dest + ".*"); } public boolean processRegionMatches(String localSrc, String localDest) { for (int i = localSrc.length() - localDest.length(); i >= 0; i--) if (localSrc.regionMatches(true, i, localDest, 0, localDest.length())) return true; return false; } // String regionMatches() @Benchmark public boolean regionMatches() { return processRegionMatches(src, dest); }
// Pattern CASE_INSENSITIVE with regexp @Benchmark public boolean patternCaseInsensitiveRegexp() { return pattern.matcher(src) .find(); } // Apache Commons StringUtils containsIgnoreCase @Benchmark public boolean apacheCommonsStringUtils() { return org.apache.commons.lang3.StringUtils.containsIgnoreCase(src, dest); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\contains\CaseInsensitiveWorkarounds.java
1
请在Spring Boot框架中完成以下Java代码
private static class OAuth2LoginBeanConfig implements ApplicationContextAware { private ApplicationContext context; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } @SuppressWarnings({ "unchecked", "unused" }) Map<String, String> getLoginLinks() { Iterable<ClientRegistration> clientRegistrations = null; ClientRegistrationRepository clientRegistrationRepository = this.context .getBean(ClientRegistrationRepository.class); ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class); if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) { clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository; } if (clientRegistrations == null) { return Collections.emptyMap(); } String authorizationRequestBaseUri = DEFAULT_AUTHORIZATION_REQUEST_BASE_URI; Map<String, String> loginUrlToClientName = new HashMap<>(); clientRegistrations.forEach((registration) -> loginUrlToClientName.put( authorizationRequestBaseUri + "/" + registration.getRegistrationId(), registration.getClientName())); return loginUrlToClientName; } } @Deprecated static class EntryPointMatcherFactoryBean implements FactoryBean<RequestMatcher> { private final RequestMatcher entryPointMatcher; EntryPointMatcherFactoryBean(RequestMatcher loginPageMatcher, RequestMatcher faviconMatcher) { RequestMatcher defaultEntryPointMatcher = getAuthenticationEntryPointMatcher(); RequestMatcher defaultLoginPageMatcher = new AndRequestMatcher( new OrRequestMatcher(loginPageMatcher, faviconMatcher), defaultEntryPointMatcher); RequestMatcher notXRequestedWith = new NegatedRequestMatcher( new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest")); this.entryPointMatcher = new AndRequestMatcher(notXRequestedWith, new NegatedRequestMatcher(defaultLoginPageMatcher)); } private RequestMatcher getAuthenticationEntryPointMatcher() { ContentNegotiationStrategy contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
MediaTypeRequestMatcher mediaMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy, MediaType.APPLICATION_XHTML_XML, new MediaType("image", "*"), MediaType.TEXT_HTML, MediaType.TEXT_PLAIN); mediaMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); RequestMatcher notXRequestedWith = new NegatedRequestMatcher( new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest")); return new AndRequestMatcher(Arrays.asList(notXRequestedWith, mediaMatcher)); } @Override public RequestMatcher getObject() { return this.entryPointMatcher; } @Override public Class<?> getObjectType() { return RequestMatcher.class; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2LoginBeanDefinitionParser.java
2
请完成以下Java代码
public class SumUpCardReaderExternalId { @NonNull private final String value; private SumUpCardReaderExternalId(@NonNull final String value) { final String valueNorm = StringUtils.trimBlankToNull(value); if (valueNorm == null) { throw new AdempiereException("Invalid card reader id: " + value); } this.value = valueNorm; } @JsonCreator @NonNull public static SumUpCardReaderExternalId ofString(@NonNull final String value) { return new SumUpCardReaderExternalId(value); }
@Nullable public static SumUpCardReaderExternalId ofNullableString(@Nullable final String value) { final String valueNorm = StringUtils.trimBlankToNull(value); return valueNorm != null ? new SumUpCardReaderExternalId(valueNorm) : null; } @Override @Deprecated public String toString() {return getAsString();} @JsonValue public String getAsString() {return value;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpCardReaderExternalId.java
1
请完成以下Java代码
public class UserOauth implements Serializable { @Serial private static final long serialVersionUID = 1L; /** * 主键 */ @JsonSerialize(using = ToStringSerializer.class) @Schema(description = "主键") @TableId(value = "id", type = IdType.ASSIGN_ID) private Long id; /** * 租户ID */ private String tenantId; /** * 第三方系统用户ID */ private String uuid; /** * 用户ID */ @JsonSerialize(using = ToStringSerializer.class) @Schema(description = "用户主键") private Long userId; /** * 用户名 */ private String username; /** * 用户昵称 */ private String nickname; /** * 用户头像 */ private String avatar; /**
* 用户网址 */ private String blog; /** * 所在公司 */ private String company; /** * 位置 */ private String location; /** * 用户邮箱 */ private String email; /** * 用户备注(各平台中的用户个人介绍) */ private String remark; /** * 性别 */ private String gender; /** * 用户来源 */ private String source; }
repos\SpringBlade-master\blade-service-api\blade-user-api\src\main\java\org\springblade\system\user\entity\UserOauth.java
1
请完成以下Java代码
public void setAppname(String appname) { this.appname = appname; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getAddressType() { return addressType; } public void setAddressType(int addressType) { this.addressType = addressType; }
public String getAddressList() { return addressList; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public void setAddressList(String addressList) { this.addressList = addressList; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobGroup.java
1
请完成以下Java代码
public boolean contains(PropertyKey<?> property) { return properties.containsKey(property.getName()); } /** * Returns <code>true</code> if this properties contains a mapping for the specified property key. * * @param property * the property key whose presence is to be tested * @return <code>true</code> if this properties contains a mapping for the specified property key */ public boolean contains(PropertyListKey<?> property) { return properties.containsKey(property.getName()); } /** * Returns <code>true</code> if this properties contains a mapping for the specified property key. * * @param property * the property key whose presence is to be tested * @return <code>true</code> if this properties contains a mapping for the specified property key */ public boolean contains(PropertyMapKey<?, ?> property) { return properties.containsKey(property.getName()); } /**
* Returns a map view of this properties. Changes to the map are not reflected * to the properties. * * @return a map view of this properties */ public Map<String, Object> toMap() { return new HashMap<String, Object>(properties); } @Override public String toString() { return "Properties [properties=" + properties + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\Properties.java
1
请完成以下Java代码
public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Picking_Job_ID (final int M_Picking_Job_ID) { if (M_Picking_Job_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID); } @Override public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() {
return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setPickingSlot (final java.lang.String PickingSlot) { set_Value (COLUMNNAME_PickingSlot, PickingSlot); } @Override public java.lang.String getPickingSlot() { return get_ValueAsString(COLUMNNAME_PickingSlot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_PickingSlot.java
1
请在Spring Boot框架中完成以下Java代码
public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException { ps.setInt(i, parameter.getCode()); } @Override public E getNullableResult(ResultSet rs, String columnName) throws SQLException { int code = rs.getInt(columnName); return rs.wasNull() ? null : codeOf(code); } @Override public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException { int code = rs.getInt(columnIndex); return rs.wasNull() ? null : codeOf(code);
} @Override public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { int code = cs.getInt(columnIndex); return cs.wasNull() ? null : codeOf(code); } private E codeOf(int code){ try { return EnumUtil.codeOf(type, code); } catch (Exception ex) { throw new IllegalArgumentException("Cannot convert " + code + " to " + type.getSimpleName() + " by code value.", ex); } } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\typehandler\EnumTypeHandler.java
2
请完成以下Java代码
public boolean isWillingToCommit () { Object oo = get_Value(COLUMNNAME_IsWillingToCommit); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Private Note. @param PrivateNote Private Note - not visible to the other parties */ public void setPrivateNote (String PrivateNote) { set_Value (COLUMNNAME_PrivateNote, PrivateNote);
} /** Get Private Note. @return Private Note - not visible to the other parties */ public String getPrivateNote () { return (String)get_Value(COLUMNNAME_PrivateNote); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Bid.java
1
请在Spring Boot框架中完成以下Java代码
public State clone() { State state = new State(arcs.length - 1); state.stack = new ArrayDeque<Integer>(stack); for (int dependent = 0; dependent < arcs.length; dependent++) { if (arcs[dependent] != null) { Edge head = arcs[dependent]; state.arcs[dependent] = head; int h = head.headIndex; if (rightMostArcs[h] != 0) { state.rightMostArcs[h] = rightMostArcs[h]; state.rightValency[h] = rightValency[h]; state.rightDepLabels[h] = rightDepLabels[h]; }
if (leftMostArcs[h] != 0) { state.leftMostArcs[h] = leftMostArcs[h]; state.leftValency[h] = leftValency[h]; state.leftDepLabels[h] = leftDepLabels[h]; } } } state.rootIndex = rootIndex; state.bufferHead = bufferHead; state.maxSentenceSize = maxSentenceSize; state.emptyFlag = emptyFlag; return state; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\configuration\State.java
2
请完成以下Java代码
public class JmxInvoker { public static void main(String... args) throws Exception { String serviceURL = args[0]; String name = args[1]; String operation = args[2]; String attributeValue = null; if (args.length > 3) { attributeValue = args[3]; } String result = execute(serviceURL, name, operation, attributeValue); System.out.println(result); } public static String execute(String url, String mBeanName, String operation, String attributeValue) { try {
JmxConnectionWrapper connection = new JmxConnectionWrapper(url, mBeanName); if (connection.hasAttribute(operation)) { Object value = connection.attributeValue(operation, attributeValue); return operation + "=" + value; } else { Object result = connection.invoke(operation); return operation + "(): " + result; } } catch (Exception e) { e.printStackTrace(); return e.getClass() + ": " + e.getMessage(); } } }
repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\jmxshell\custom\JmxInvoker.java
1