instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
final class OidcUserRequestUtils { /** * Determines if an {@link OidcUserRequest} should attempt to retrieve the user info. * Will return true if all the following are true: * * <ul> * <li>The user info endpoint is defined on the ClientRegistration</li> * <li>The Client Registration uses the * {@link AuthorizationGrantType#AUTHORIZATION_CODE}</li> * </ul> * @param userRequest * @return */ static boolean shouldRetrieveUserInfo(OidcUserRequest userRequest) { // Auto-disabled if UserInfo Endpoint URI is not provided ClientRegistration.ProviderDetails providerDetails = userRequest.getClientRegistration().getProviderDetails(); if (StringUtils.hasLength(providerDetails.getUserInfoEndpoint().getUri()) && AuthorizationGrantType.AUTHORIZATION_CODE .equals(userRequest.getClientRegistration().getAuthorizationGrantType())) { return true; } return false; } static OidcUser getUser(OidcUserSource userMetadata) { OidcUserRequest userRequest = userMetadata.getUserRequest();
OidcUserInfo userInfo = userMetadata.getUserInfo(); Set<GrantedAuthority> authorities = new LinkedHashSet<>(); ClientRegistration.ProviderDetails providerDetails = userRequest.getClientRegistration().getProviderDetails(); String userNameAttributeName = providerDetails.getUserInfoEndpoint().getUserNameAttributeName(); if (StringUtils.hasText(userNameAttributeName)) { authorities.add(new OidcUserAuthority(userRequest.getIdToken(), userInfo, userNameAttributeName)); } else { authorities.add(new OidcUserAuthority(userRequest.getIdToken(), userInfo)); } OAuth2AccessToken token = userRequest.getAccessToken(); for (String scope : token.getScopes()) { authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope)); } if (StringUtils.hasText(userNameAttributeName)) { return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo, userNameAttributeName); } return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo); } private OidcUserRequestUtils() { } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\userinfo\OidcUserRequestUtils.java
1
请在Spring Boot框架中完成以下Java代码
private DefaultSpringSecurityContextSource build() { if (this.url == null) { startEmbeddedLdapServer(); } DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(getProviderUrl()); if (this.managerDn != null) { contextSource.setUserDn(this.managerDn); if (this.managerPassword == null) { throw new IllegalStateException("managerPassword is required if managerDn is supplied"); } contextSource.setPassword(this.managerPassword); } contextSource = postProcess(contextSource); return contextSource; } private void startEmbeddedLdapServer() { if (unboundIdPresent) { UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif); unboundIdContainer.setPort(getPort()); postProcess(unboundIdContainer); this.port = unboundIdContainer.getPort(); } else { throw new IllegalStateException("Embedded LDAP server is not provided"); } } private int getPort() { if (this.port == null) { this.port = getDefaultPort(); } return this.port; }
private int getDefaultPort() { try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) { return serverSocket.getLocalPort(); } catch (IOException ex) { return RANDOM_PORT; } } private String getProviderUrl() { if (this.url == null) { return "ldap://127.0.0.1:" + getPort() + "/" + this.root; } return this.url; } private ContextSourceBuilder() { } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\ldap\LdapAuthenticationProviderConfigurer.java
2
请完成以下Java代码
public static Boolean validKeyword(String keyword) { String regex = "^[a-zA-Z0-9\u4E00-\u9FA5]+$"; Pattern pattern = Pattern.compile(regex); Matcher match = pattern.matcher(keyword); return match.matches(); } /** * 判断是否是邮箱 * * @param emailStr * @return */ public static boolean isEmail(String emailStr) { Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr); return matcher.find(); } /** * 判断是否是网址
* * @param urlString * @return */ public static boolean isURL(String urlString) { String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$"; Pattern pattern = Pattern.compile(regex); if (pattern.matcher(urlString).matches()) { return true; } else { return false; } } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\util\PatternUtil.java
1
请完成以下Java代码
public DocumentEntityDescriptor getEntityDescriptor() { return entityDescriptor; } @Override public ETag getETag() { return eTag; } // public static final class Builder { private DocumentLayoutDescriptor layout; private DocumentEntityDescriptor entityDescriptor; private Builder() {
} public DocumentDescriptor build() { return new DocumentDescriptor(this); } public Builder setLayout(final DocumentLayoutDescriptor layout) { this.layout = layout; return this; } public Builder setEntityDescriptor(final DocumentEntityDescriptor entityDescriptor) { this.entityDescriptor = entityDescriptor; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentDescriptor.java
1
请完成以下Java代码
public void migrateProcessInstances(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); getProcessMigrationService().migrateProcessInstancesOfProcessDefinition(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, document); } @Override public Batch batchMigrateProcessInstances(String processDefinitionId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); return getProcessMigrationService().batchMigrateProcessInstancesOfProcessDefinition(processDefinitionId, document); } @Override public Batch batchMigrateProcessInstances(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); return getProcessMigrationService().batchMigrateProcessInstancesOfProcessDefinition(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, document);
} @Override public ProcessInstanceMigrationValidationResult validateMigrationOfProcessInstances(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); return getProcessMigrationService().validateMigrationForProcessInstancesOfProcessDefinition(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, document); } protected ProcessMigrationService getProcessMigrationService() { if (processInstanceMigrationService == null) { throw new FlowableException("ProcessInstanceMigrationService cannot be null, Obtain your builder instance from the ProcessInstanceMigrationService to access this feature"); } return processInstanceMigrationService; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\migration\ProcessInstanceMigrationBuilderImpl.java
1
请完成以下Java代码
public static byte[] encrypt(byte[] content, String aesTextKey) { return encrypt(content, Objects.requireNonNull(aesTextKey).getBytes(DEFAULT_CHARSET)); } /** * Base64解密 * * @param content 文本内容 * @param aesTextKey 文本密钥 * @return {String} */ @Nullable public static String decryptToString(@Nullable String content, @Nullable String aesTextKey) { if (!StringUtils.hasText(content) || !StringUtils.hasText(aesTextKey)) { return null; } byte[] hexBytes = decrypt(Base64.getDecoder().decode(content.getBytes(DEFAULT_CHARSET)), aesTextKey); return new String(hexBytes, DEFAULT_CHARSET); } /** * 解密 * * @param content 内容 * @param aesTextKey 文本密钥 * @return byte[] */ public static byte[] decrypt(byte[] content, String aesTextKey) { return decrypt(content, Objects.requireNonNull(aesTextKey).getBytes(DEFAULT_CHARSET)); } /** * 解密 * * @param content 内容 * @param aesKey 密钥 * @return byte[] */ public static byte[] encrypt(byte[] content, byte[] aesKey) { return aes(Pkcs7Encoder.encode(content), aesKey, Cipher.ENCRYPT_MODE); } /** * 加密 * * @param encrypted 内容 * @param aesKey 密钥 * @return byte[] */ public static byte[] decrypt(byte[] encrypted, byte[] aesKey) { return Pkcs7Encoder.decode(aes(encrypted, aesKey, Cipher.DECRYPT_MODE)); } /** * ase加密 *
* @param encrypted 内容 * @param aesKey 密钥 * @param mode 模式 * @return byte[] */ @SneakyThrows private static byte[] aes(byte[] encrypted, byte[] aesKey, int mode) { Assert.isTrue(aesKey.length == 32, "IllegalAesKey, aesKey's length must be 32"); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); cipher.init(mode, keySpec, iv); return cipher.doFinal(encrypted); } /** * 提供基于PKCS7算法的加解密接口. */ private static class Pkcs7Encoder { private static final int BLOCK_SIZE = 32; private static byte[] encode(byte[] src) { int count = src.length; // 计算需要填充的位数 int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); // 获得补位所用的字符 byte pad = (byte) (amountToPad & 0xFF); byte[] pads = new byte[amountToPad]; for (int index = 0; index < amountToPad; index++) { pads[index] = pad; } int length = count + amountToPad; byte[] dest = new byte[length]; System.arraycopy(src, 0, dest, 0, count); System.arraycopy(pads, 0, dest, count, amountToPad); return dest; } private static byte[] decode(byte[] decrypted) { int pad = decrypted[decrypted.length - 1]; if (pad < 1 || pad > BLOCK_SIZE) { pad = 0; } if (pad > 0) { return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); } return decrypted; } } }
repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\utils\JwtCrypto.java
1
请完成以下Java代码
public Map<String, MetricDto> getMetrics() { return metrics; } public void setMetrics(Map<String, MetricDto> metrics) { this.metrics = metrics; } public JdkDto getJdk() { return jdk; } public void setJdk(JdkDto jdk) { this.jdk = jdk; } public Set<String> getCamundaIntegration() { return camundaIntegration; } public void setCamundaIntegration(Set<String> camundaIntegration) { this.camundaIntegration = camundaIntegration; } public LicenseKeyDataDto getLicenseKey() { return licenseKey; } public void setLicenseKey(LicenseKeyDataDto licenseKey) { this.licenseKey = licenseKey; } public Set<String> getWebapps() { return webapps; } public void setWebapps(Set<String> webapps) {
this.webapps = webapps; } public Date getDataCollectionStartDate() { return dataCollectionStartDate; } public void setDataCollectionStartDate(Date dataCollectionStartDate) { this.dataCollectionStartDate = dataCollectionStartDate; } public static InternalsDto fromEngineDto(Internals other) { LicenseKeyData licenseKey = other.getLicenseKey(); InternalsDto dto = new InternalsDto( DatabaseDto.fromEngineDto(other.getDatabase()), ApplicationServerDto.fromEngineDto(other.getApplicationServer()), licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null, JdkDto.fromEngineDto(other.getJdk())); dto.dataCollectionStartDate = other.getDataCollectionStartDate(); dto.commands = new HashMap<>(); other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount()))); dto.metrics = new HashMap<>(); other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount()))); dto.setWebapps(other.getWebapps()); dto.setCamundaIntegration(other.getCamundaIntegration()); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\InternalsDto.java
1
请完成以下Java代码
public final class OAuth2AuthorizationResponseType implements Serializable { private static final long serialVersionUID = 620L; public static final OAuth2AuthorizationResponseType CODE = new OAuth2AuthorizationResponseType("code"); private final String value; public OAuth2AuthorizationResponseType(String value) { Assert.hasText(value, "value cannot be empty"); this.value = value; } /** * Returns the value of the authorization response type. * @return the value of the authorization response type */ public String getValue() { return this.value;
} @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } OAuth2AuthorizationResponseType that = (OAuth2AuthorizationResponseType) obj; return this.getValue().equals(that.getValue()); } @Override public int hashCode() { return this.getValue().hashCode(); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AuthorizationResponseType.java
1
请完成以下Java代码
public class PP_Order_Candidate_SetWorkstation extends ViewBasedProcessTemplate implements IProcessPrecondition { private final PPOrderCandidateService ppOrderCandidateService = SpringContextHolder.instance.getBean(PPOrderCandidateService.class); private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); private static final String PARAM_WorkStation_ID = I_PP_Order_Candidate.COLUMNNAME_WorkStation_ID; @Param(parameterName = PARAM_WorkStation_ID, mandatory = false) private ResourceId p_Workstation_ID; private final int rowsLimit = sysConfigBL.getPositiveIntValue("PP_Order_Candidate_SetWorkstation.rowsLimit", 1000); @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { ppOrderCandidateService.setWorkstationId(getSelectedPPOrderCandidateIds(), p_Workstation_ID); return MSG_OK; } private ImmutableSet<PPOrderCandidateId> getSelectedPPOrderCandidateIds() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isAll()) { return getView().streamByIds(selectedRowIds) .limit(rowsLimit) .map(PP_Order_Candidate_SetWorkstation::extractPPOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } else { return selectedRowIds.stream() .map(PP_Order_Candidate_SetWorkstation::toPPOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } } @NonNull private static PPOrderCandidateId extractPPOrderCandidateId(final IViewRow row) {return toPPOrderCandidateId(row.getId());} @NonNull private static PPOrderCandidateId toPPOrderCandidateId(final DocumentId rowId) {return PPOrderCandidateId.ofRepoId(rowId.toInt());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.webui\src\main\java\de\metas\manufacturing\webui\process\PP_Order_Candidate_SetWorkstation.java
1
请在Spring Boot框架中完成以下Java代码
public class AttributeSetInstanceAwareFactoryService implements IAttributeSetInstanceAwareFactoryService { private final Map<String, IAttributeSetInstanceAwareFactory> tableName2Factory = new HashMap<>(); /** * Factory to be used when no other factory was found */ private final IAttributeSetInstanceAwareFactory defaultFactory; public AttributeSetInstanceAwareFactoryService() { defaultFactory = new GenericAttributeSetInstanceAwareFactory(); } @Override public void registerFactoryForTableName( @NonNull final String tableName, @NonNull final IAttributeSetInstanceAwareFactory factory) { tableName2Factory.put(tableName, factory); } @Override public IAttributeSetInstanceAware createOrNull(final Object referencedObj) { if (referencedObj == null) { return null; } // If already an ASI aware, return it if (referencedObj instanceof IAttributeSetInstanceAware) { return (IAttributeSetInstanceAware)referencedObj; }
final IAttributeSetInstanceAwareFactory factory; final String tableName = InterfaceWrapperHelper.getModelTableNameOrNull(referencedObj); if (tableName != null) { factory = getFactoryForTableNameOrDefault(tableName); } else { return null; } return factory.createOrNull(referencedObj); } private IAttributeSetInstanceAwareFactory getFactoryForTableNameOrDefault(@NonNull final String tableName) { final IAttributeSetInstanceAwareFactory factory = tableName2Factory.get(tableName); if (factory != null) { return factory; } return defaultFactory; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\asi_aware\factory\impl\AttributeSetInstanceAwareFactoryService.java
2
请完成以下Java代码
private List<IContextMenuAction> getInstances(final IContextMenuActionContext menuCtx, final List<Class<? extends IContextMenuAction>> actionClasses) { if (actionClasses == null || actionClasses.isEmpty()) { return Collections.emptyList(); } final List<IContextMenuAction> result = new ArrayList<>(); for (final Class<? extends IContextMenuAction> actionClass : actionClasses) { final IContextMenuAction action = getInstance(menuCtx, actionClass); if (action != null) { result.add(action); } } return result; } private IContextMenuAction getInstance(final IContextMenuActionContext menuCtx, final Class<? extends IContextMenuAction> actionClass) { try { final IContextMenuAction action = actionClass.newInstance(); action.setContext(menuCtx); if (!action.isAvailable()) { return null; } return action; } catch (Exception e) { logger.warn("Cannot create action for " + actionClass + ": " + e.getLocalizedMessage() + " [SKIP]", e); return null; } } // @Cached(cacheName = I_AD_Field_ContextMenu.Table_Name + "#By#AD_Client_ID") // not needed, we are caching the classname lists private final List<I_AD_Field_ContextMenu> retrieveContextMenuForClient(@CacheCtx final Properties ctx, final int adClientId)
{ return Services.get(IQueryBL.class).createQueryBuilder(I_AD_Field_ContextMenu.class, ctx, ITrx.TRXNAME_None) .addInArrayOrAllFilter(I_AD_Field_ContextMenu.COLUMN_AD_Client_ID, 0, adClientId) .addOnlyActiveRecordsFilter() // .orderBy() .addColumn(I_AD_Field_ContextMenu.COLUMN_SeqNo) .addColumn(I_AD_Field_ContextMenu.COLUMN_AD_Field_ContextMenu_ID) .endOrderBy() // .create() .list(I_AD_Field_ContextMenu.class); } @Override public IContextMenuActionContext createContext(final VEditor editor) { final VTable vtable = null; final int viewRow = IContextMenuActionContext.ROW_NA; final int viewColumn = IContextMenuActionContext.COLUMN_NA; return createContext(editor, vtable, viewRow, viewColumn); } @Override public IContextMenuActionContext createContext(final VEditor editor, final VTable vtable, final int rowIndexView, final int columnIndexView) { return new DefaultContextMenuActionContext(editor, vtable, rowIndexView, columnIndexView); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\impl\ContextMenuProvider.java
1
请在Spring Boot框架中完成以下Java代码
private static class SumUpConfigMap { public static SumUpConfigMap EMPTY = new SumUpConfigMap(ImmutableList.of()); private final ImmutableMap<SumUpConfigId, SumUpConfig> byId; private final SumUpConfig defaultConfig; private SumUpConfigMap(final List<SumUpConfig> list) { this.byId = Maps.uniqueIndex(list, SumUpConfig::getId); final List<SumUpConfig> activeConfigs = list.stream() .filter(SumUpConfig::isActive) .collect(ImmutableList.toImmutableList()); this.defaultConfig = activeConfigs.size() == 1 ? activeConfigs.get(0) : null; } public SumUpConfig getById(final @NonNull SumUpConfigId id) { final SumUpConfig config = byId.get(id); if (config == null) {
throw new AdempiereException("No SumUp config found for " + id); } return config; } public SumUpConfig getDefault() { if (defaultConfig == null) { throw new AdempiereException("No default SumUp config found"); } return defaultConfig; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\repository\SumUpConfigRepository.java
2
请完成以下Java代码
public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isRequestHeaders() { return requestHeaders; } public void setRequestHeaders(boolean requestHeaders) { this.requestHeaders = requestHeaders; } public boolean isRequestBody() { return requestBody; } public void setRequestBody(boolean requestBody) { this.requestBody = requestBody;
} public boolean isResponseHeaders() { return responseHeaders; } public void setResponseHeaders(boolean responseHeaders) { this.responseHeaders = responseHeaders; } public boolean isResponseBody() { return responseBody; } public void setResponseBody(boolean responseBody) { this.responseBody = responseBody; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\global\LoggingGlobalFilterProperties.java
1
请在Spring Boot框架中完成以下Java代码
public class JobCodeController { @Resource private XxlJobInfoDao xxlJobInfoDao; @Resource private XxlJobLogGlueDao xxlJobLogGlueDao; @RequestMapping public String index(HttpServletRequest request, Model model, int jobId) { XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId); List<XxlJobLogGlue> jobLogGlues = xxlJobLogGlueDao.findByJobId(jobId); if (jobInfo == null) { throw new RuntimeException(I18nUtil.getString("jobinfo_glue_jobid_unvalid")); } if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType())) { throw new RuntimeException(I18nUtil.getString("jobinfo_glue_gluetype_unvalid")); } // valid permission JobInfoController.validPermission(request, jobInfo.getJobGroup()); // Glue类型-字典 model.addAttribute("GlueTypeEnum", GlueTypeEnum.values()); model.addAttribute("jobInfo", jobInfo); model.addAttribute("jobLogGlues", jobLogGlues); return "jobcode/jobcode.index"; } @RequestMapping("/save") @ResponseBody public ReturnT<String> save(Model model, int id, String glueSource, String glueRemark) { // valid if (glueRemark==null) { return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_glue_remark")) ); } if (glueRemark.length()<4 || glueRemark.length()>100) {
return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_remark_limit")); } XxlJobInfo exists_jobInfo = xxlJobInfoDao.loadById(id); if (exists_jobInfo == null) { return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_jobid_unvalid")); } // update new code exists_jobInfo.setGlueSource(glueSource); exists_jobInfo.setGlueRemark(glueRemark); exists_jobInfo.setGlueUpdatetime(new Date()); exists_jobInfo.setUpdateTime(new Date()); xxlJobInfoDao.update(exists_jobInfo); // log old code XxlJobLogGlue xxlJobLogGlue = new XxlJobLogGlue(); xxlJobLogGlue.setJobId(exists_jobInfo.getId()); xxlJobLogGlue.setGlueType(exists_jobInfo.getGlueType()); xxlJobLogGlue.setGlueSource(glueSource); xxlJobLogGlue.setGlueRemark(glueRemark); xxlJobLogGlue.setAddTime(new Date()); xxlJobLogGlue.setUpdateTime(new Date()); xxlJobLogGlueDao.save(xxlJobLogGlue); // remove code backup more than 30 xxlJobLogGlueDao.removeOld(exists_jobInfo.getId(), 30); return ReturnT.SUCCESS; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobCodeController.java
2
请完成以下Java代码
public static Long computeMinimumDistance(Long[] arrayA, Long[] arrayB) { int aIndex = 0; int bIndex = 0; long min = Math.abs(arrayA[0] - arrayB[0]); while (true) { if (arrayA[aIndex] > arrayB[bIndex]) { bIndex++; } else { aIndex++; } if (aIndex >= arrayA.length || bIndex >= arrayB.length) { break; } if (Math.abs(arrayA[aIndex] - arrayB[bIndex]) < min) {
min = Math.abs(arrayA[aIndex] - arrayB[bIndex]); } } return min; } public static Long computeAverageDistance(Long[] arrayA, Long[] arrayB) { Long totalA = 0L; Long totalB = 0L; for (Long a : arrayA) totalA += a; for (Long b : arrayB) totalB += b; return Math.abs(totalA / arrayA.length - totalB / arrayB.length); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ArrayDistance.java
1
请完成以下Java代码
public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public Rule toRule() { return null; } @Override public boolean equals(Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiDefinitionEntity entity = (ApiDefinitionEntity) o; return Objects.equals(id, entity.id) && Objects.equals(app, entity.app) && Objects.equals(ip, entity.ip) && Objects.equals(port, entity.port) && Objects.equals(gmtCreate, entity.gmtCreate) && Objects.equals(gmtModified, entity.gmtModified) && Objects.equals(apiName, entity.apiName) && Objects.equals(predicateItems, entity.predicateItems); } @Override public int hashCode() { return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, apiName, predicateItems); } @Override public String toString() { return "ApiDefinitionEntity{" + "id=" + id + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", apiName='" + apiName + '\'' + ", predicateItems=" + predicateItems + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\ApiDefinitionEntity.java
1
请完成以下Java代码
public static <V> LinkedList<ResultTerm<V>> segmentReverseOrder(final char[] charArray, AhoCorasickDoubleArrayTrie<V> trie) { LinkedList<ResultTerm<V>> termList = new LinkedList<ResultTerm<V>>(); final ResultTerm<V>[] wordNet = new ResultTerm[charArray.length + 1]; trie.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<V>() { @Override public void hit(int begin, int end, V value) { if (wordNet[end] == null || wordNet[end].word.length() < end - begin) { wordNet[end] = new ResultTerm<V>(new String(charArray, begin, end - begin), value, begin); } } }); for (int i = charArray.length; i > 0;) { if (wordNet[i] == null) { StringBuilder sbTerm = new StringBuilder(); int offset = i - 1; byte preCharType = CharType.get(charArray[offset]);
while (i > 0 && wordNet[i] == null && CharType.get(charArray[i - 1]) == preCharType) { sbTerm.append(charArray[i - 1]); preCharType = CharType.get(charArray[i - 1]); --i; } termList.addFirst(new ResultTerm<V>(sbTerm.reverse().toString(), null, offset)); } else { termList.addFirst(wordNet[i]); i -= wordNet[i].word.length(); } } return termList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Other\CommonAhoCorasickSegmentUtil.java
1
请完成以下Java代码
public void setIsInstanceAttribute (final boolean IsInstanceAttribute) { set_Value (COLUMNNAME_IsInstanceAttribute, IsInstanceAttribute); } @Override public boolean isInstanceAttribute() { return get_ValueAsBoolean(COLUMNNAME_IsInstanceAttribute); } /** * MandatoryType AD_Reference_ID=324 * Reference name: M_AttributeSet MandatoryType */ public static final int MANDATORYTYPE_AD_Reference_ID=324; /** Not Mandatary = N */ public static final String MANDATORYTYPE_NotMandatary = "N"; /** Always Mandatory = Y */ public static final String MANDATORYTYPE_AlwaysMandatory = "Y"; /** WhenShipping = S */ public static final String MANDATORYTYPE_WhenShipping = "S"; @Override public void setMandatoryType (final java.lang.String MandatoryType) { set_Value (COLUMNNAME_MandatoryType, MandatoryType); } @Override public java.lang.String getMandatoryType() { return get_ValueAsString(COLUMNNAME_MandatoryType); }
@Override public void setM_AttributeSet_ID (final int M_AttributeSet_ID) { if (M_AttributeSet_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, M_AttributeSet_ID); } @Override public int getM_AttributeSet_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSet_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSet.java
1
请完成以下Java代码
public class ShipperGatewayException extends RuntimeException { private final ImmutableList<ShipperErrorMessage> shipperErrorMessages; public ShipperGatewayException(final String message) { super(message); this.shipperErrorMessages = ImmutableList.of(); } public ShipperGatewayException(final List<ShipperErrorMessage> shipperErrorMessages) { super(extractMessage(shipperErrorMessages)); this.shipperErrorMessages = shipperErrorMessages != null ? ImmutableList.copyOf(shipperErrorMessages) : ImmutableList.of(); } private static String extractMessage(final List<ShipperErrorMessage> shipperErrorMessages) { if (shipperErrorMessages == null || shipperErrorMessages.isEmpty()) { return "Unknown shipper gateway error"; } else if (shipperErrorMessages.size() == 1)
{ final ShipperErrorMessage shipperErrorMessage = shipperErrorMessages.get(0); return shipperErrorMessage.getMessage(); } else { return shipperErrorMessages.stream() .map(ShipperErrorMessage::getMessage) .collect(Collectors.joining("; ")); } } public List<ShipperErrorMessage> getShipperErrorMessages() { return shipperErrorMessages; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\exceptions\ShipperGatewayException.java
1
请完成以下Java代码
static class Builder { private Promise<Void> future; private String topic; private Set<MqttPendingHandler> handlers; private MqttSubscribeMessage subscribeMessage; private String ownerId; private PendingOperation pendingOperation; private MqttClientConfig.RetransmissionConfig retransmissionConfig; Builder future(Promise<Void> future) { this.future = future; return this; } Builder topic(String topic) { this.topic = topic; return this; } Builder handlers(Set<MqttPendingHandler> handlers) { this.handlers = handlers; return this; } Builder subscribeMessage(MqttSubscribeMessage subscribeMessage) { this.subscribeMessage = subscribeMessage; return this; } Builder ownerId(String ownerId) { this.ownerId = ownerId; return this;
} Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) { this.retransmissionConfig = retransmissionConfig; return this; } Builder pendingOperation(PendingOperation pendingOperation) { this.pendingOperation = pendingOperation; return this; } MqttPendingSubscription build() { return new MqttPendingSubscription(future, topic, handlers, subscribeMessage, ownerId, retransmissionConfig, pendingOperation); } } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingSubscription.java
1
请在Spring Boot框架中完成以下Java代码
public class RestTemplateConfiguration { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } @RestController static class TestController { @Autowired private DiscoveryClient discoveryClient; @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; @GetMapping("/hello") public String hello(String name) { // 获得服务 `demo-provider` 的一个实例 ServiceInstance instance; if (true) { // 获取服务 `demo-provider` 对应的实例列表 List<ServiceInstance> instances = discoveryClient.getInstances("demo-provider"); // 选择第一个 instance = instances.size() > 0 ? instances.get(0) : null; } else {
instance = loadBalancerClient.choose("demo-provider"); } // 发起调用 if (instance == null) { throw new IllegalStateException("获取不到实例"); } String targetUrl = instance.getUri() + "/echo?name=" + name; String response = restTemplate.getForObject(targetUrl, String.class); // 返回结果 return "consumer:" + response; } } }
repos\SpringBoot-Labs-master\labx-01-spring-cloud-alibaba-nacos-discovery\labx-01-sca-nacos-discovery-demo01-consumer\src\main\java\cn\iocoder\springcloudalibaba\labx01\nacosdemo\consumer\DemoConsumerApplication.java
2
请在Spring Boot框架中完成以下Java代码
public class SessionRestController { static final String ENDPOINT = Application.ENDPOINT_ROOT + "/session"; private final ILoginService loginService; private final UserConfirmationService userConfirmationService; public SessionRestController( @NonNull final ILoginService loginService, @NonNull final UserConfirmationService userConfirmationService) { this.loginService = loginService; this.userConfirmationService = userConfirmationService; } @GetMapping("/") public JsonSessionInfo getSessionInfo() { final User user = loginService.getLoggedInUser(); final Locale locale = loginService.getLocale(); final long countUnconfirmed = userConfirmationService.getCountUnconfirmed(user); final LocalDate today = LocalDate.now(); final YearWeek week = YearWeekUtil.ofLocalDate(today); return JsonSessionInfo.builder() .loggedIn(true) .email(user.getEmail()) .language(LanguageKey.ofLocale(locale).getAsString()) // .date(today) .dayCaption(DateUtils.getDayName(today, locale)) .week(YearWeekUtil.toJsonString(week)) .weekCaption(YearWeekUtil.toDisplayName(week)) // .countUnconfirmed(countUnconfirmed) .build(); } @PostMapping("/login") public JsonSessionInfo login(@RequestBody @NonNull final JsonLoginRequest request) { try { loginService.login(request.getEmail(), request.getPassword()); return getSessionInfo(); } catch (final Exception ex) { return JsonSessionInfo.builder() .loggedIn(false) .loginError(ex.getLocalizedMessage()) .build(); } } @GetMapping("/logout") public void logout() { loginService.logout(); }
@GetMapping("/resetUserPassword") public void resetUserPasswordRequest(@RequestParam("email") final String email) { final String passwordResetToken = loginService.generatePasswordResetKey(email); loginService.sendPasswordResetKey(email, passwordResetToken); } @GetMapping("/resetUserPasswordConfirm") public JsonPasswordResetResponse resetUserPasswordConfirm(@RequestParam("token") final String token) { final User user = loginService.resetPassword(token); loginService.login(user); return JsonPasswordResetResponse.builder() .email(user.getEmail()) .language(user.getLanguageKeyOrDefault().getAsString()) .newPassword(user.getPassword()) .build(); } @PostMapping("/confirmDataEntry") public ConfirmDataEntryResponse confirmDataEntry() { final User user = loginService.getLoggedInUser(); userConfirmationService.confirmUserEntries(user); return ConfirmDataEntryResponse.builder() .countUnconfirmed(userConfirmationService.getCountUnconfirmed(user)) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\session\SessionRestController.java
2
请在Spring Boot框架中完成以下Java代码
public class WebController { @RequestMapping(name="/getUser", method= RequestMethod.POST) public User getUser() { User user=new User(); user.setName("小明"); user.setAge(12); user.setPass("123456"); return user; } @RequestMapping("/getUsers") public List<User> getUsers() { List<User> users=new ArrayList<User>(); User user1=new User(); user1.setName("neo"); user1.setAge(30); user1.setPass("neo123"); users.add(user1); User user2=new User(); user2.setName("小明"); user2.setAge(12); user2.setPass("123456"); users.add(user2); return users; } @RequestMapping(value="get/{name}", method=RequestMethod.GET) public User get(@PathVariable String name) {
User user=new User(); user.setName(name); return user; } @RequestMapping("/saveUser") public void saveUser(@Valid User user,BindingResult result) { System.out.println("user:"+user); if(result.hasErrors()) { List<ObjectError> list = result.getAllErrors(); for (ObjectError error : list) { System.out.println(error.getCode()+ "-" + error.getDefaultMessage()); } } } }
repos\spring-boot-leaning-master\1.x\第03课:快速体验 Web 开发\spring-boot-web\src\main\java\com\neo\web\WebController.java
2
请完成以下Java代码
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 Organization. @param Org_ID Organizational entity within client */ public void setOrg_ID (int Org_ID) { if (Org_ID < 1) set_Value (COLUMNNAME_Org_ID, null); else set_Value (COLUMNNAME_Org_ID, Integer.valueOf(Org_ID)); } /** Get Organization. @return Organizational entity within client */ public int getOrg_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Org_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Goal getPA_Goal() throws RuntimeException { return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name) .getPO(getPA_Goal_ID(), get_TrxName()); } /** Set Goal. @param PA_Goal_ID Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID) {
if (PA_Goal_ID < 1) set_Value (COLUMNNAME_PA_Goal_ID, null); else set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID)); } /** Get Goal. @return Performance Goal */ public int getPA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Goal Restriction. @param PA_GoalRestriction_ID Performance Goal Restriction */ public void setPA_GoalRestriction_ID (int PA_GoalRestriction_ID) { if (PA_GoalRestriction_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_GoalRestriction_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_GoalRestriction_ID, Integer.valueOf(PA_GoalRestriction_ID)); } /** Get Goal Restriction. @return Performance Goal Restriction */ public int getPA_GoalRestriction_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_GoalRestriction_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_PA_GoalRestriction.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<HttpStatusCode> uploadPdf(final Resource resource) { final URI url = UriComponentsBuilder.fromHttpUrl(EXTERNAL_UPLOAD_URL).build().toUri(); Mono<HttpStatusCode> httpStatusMono = webClient.post() .uri(url) .contentType(MediaType.APPLICATION_PDF) .body(BodyInserters.fromResource(resource)) .exchangeToMono(response -> { if (response.statusCode().equals(HttpStatus.OK)) { return response.bodyToMono(HttpStatus.class).thenReturn(response.statusCode()); } else { throw new ServiceException("Error uploading file"); } }); return httpStatusMono; } public Mono<HttpStatusCode> uploadMultipart(final MultipartFile multipartFile) {
final URI url = UriComponentsBuilder.fromHttpUrl(EXTERNAL_UPLOAD_URL).build().toUri(); final MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("file", multipartFile.getResource()); Mono<HttpStatusCode> httpStatusMono = webClient.post() .uri(url) .contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData(builder.build())) .exchangeToMono(response -> { if (response.statusCode().equals(HttpStatus.OK)) { return response.bodyToMono(HttpStatus.class).thenReturn(response.statusCode()); } else { throw new ServiceException("Error uploading file"); } }); return httpStatusMono; } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client-2\src\main\java\com\baeldung\service\ReactiveUploadService.java
2
请完成以下Java代码
public static void conditionalSleep(Supplier<Boolean> shouldSleepCondition, long interval) throws InterruptedException { long timeout = System.currentTimeMillis() + interval; long sleepInterval = interval > SMALL_INTERVAL_THRESHOLD ? DEFAULT_SLEEP_INTERVAL : SMALL_SLEEP_INTERVAL; do { Thread.sleep(sleepInterval); if (!shouldSleepCondition.get()) { break; } } while (System.currentTimeMillis() < timeout); } /** * Sleep for the desired timeout, as long as shouldSleepCondition supplies true. * This method requires that the consumer is paused; otherwise, ConsumerRecord may be lost. * Periodically calls {@code Consumer.poll(Duration.ZERO)} to prevent a paused consumer from being rebalanced. * @param shouldSleepCondition to. * @param interval the timeout. * @param consumer the kafka consumer to call poll(). * @throws InterruptedException if the thread is interrupted. */ public static void conditionalSleepWithPoll(Supplier<Boolean> shouldSleepCondition, long interval, Consumer<?, ?> consumer) throws InterruptedException { boolean isFirst = true; long timeout = System.currentTimeMillis() + interval; long sleepInterval = interval > SMALL_INTERVAL_THRESHOLD ? DEFAULT_SLEEP_INTERVAL : SMALL_SLEEP_INTERVAL; do { Thread.sleep(sleepInterval); if (!shouldSleepCondition.get()) { break; } if (isFirst) { isFirst = false; }
else { // To prevent consumer group rebalancing during retry backoff. consumer.poll(Duration.ZERO); } } while (System.currentTimeMillis() < timeout); } /** * Create a new {@link OffsetAndMetadata} using the given container and offset. * @param container a container. * @param offset an offset. * @return an offset and metadata. * @since 2.8.6 */ public static OffsetAndMetadata createOffsetAndMetadata(@Nullable MessageListenerContainer container, long offset) { Assert.state(container != null, "Container cannot be null"); final OffsetAndMetadataProvider metadataProvider = container.getContainerProperties() .getOffsetAndMetadataProvider(); if (metadataProvider != null) { return metadataProvider.provide(new DefaultListenerMetadata(container), offset); } return new OffsetAndMetadata(offset); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ListenerUtils.java
1
请完成以下Java代码
public Object get(Object key) { for (Resolver scriptResolver : scriptResolvers) { if (scriptResolver.containsKey(key)) { return scriptResolver.get(key); } } return defaultBindings.get(key); } public Object put(String name, Object value) { if (storeScriptVariables) { Object oldValue = null; if (!UNSTORED_KEYS.contains(name)) { oldValue = variableScope.getVariable(name); variableScope.setVariable(name, value); return oldValue; } } return defaultBindings.put(name, value); } public Set<Map.Entry<String, Object>> entrySet() { return variableScope.getVariables().entrySet(); } public Set<String> keySet() { return variableScope.getVariables().keySet(); } public int size() { return variableScope.getVariables().size(); } public Collection<Object> values() { return variableScope.getVariables().values(); }
public void putAll(Map<? extends String, ? extends Object> toMerge) { throw new UnsupportedOperationException(); } public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return defaultBindings.remove(key); } public void clear() { throw new UnsupportedOperationException(); } public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } public boolean isEmpty() { throw new UnsupportedOperationException(); } public void addUnstoredKey(String unstoredKey) { UNSTORED_KEYS.add(unstoredKey); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptBindings.java
1
请完成以下Java代码
public static SubscriptionProgressQueryBuilder endingRightBefore(@NonNull final I_C_SubscriptionProgress subscriptionProgress) { final I_C_Flatrate_Term term = subscriptionProgress.getC_Flatrate_Term(); return term(term).seqNoLessThan(subscriptionProgress.getSeqNo()); } public static SubscriptionProgressQueryBuilder term(@NonNull final I_C_Flatrate_Term term) { return builder().term(term); } @NonNull I_C_Flatrate_Term term; Timestamp eventDateNotBefore; Timestamp eventDateNotAfter; @Default int seqNoNotLessThan = 0; @Default int seqNoLessThan = 0; /** never {@code null}. Empty means "don't filter by status altogether". */ @Singular List<String> excludedStatuses; /** never {@code null}. Empty means "don't filter by status altogether". */ @Singular List<String> includedStatuses; /** never {@code null}. Empty means "don't filter by status altogether". */ @Singular List<String> includedContractStatuses; } /** * Loads all {@link I_C_SubscriptionProgress} records that have event type * {@link X_C_SubscriptionProgress#EVENTTYPE_Lieferung} and status {@link X_C_SubscriptionProgress#STATUS_Geplant} * or {@link X_C_SubscriptionProgress#STATUS_Verzoegert}, ordered by * {@link I_C_SubscriptionProgress#COLUMNNAME_EventDate} and {@link I_C_SubscriptionProgress#COLUMNNAME_SeqNo}. * * @param date * the records' event date is before or equal. * @param trxName * @return */ List<I_C_SubscriptionProgress> retrievePlannedAndDelayedDeliveries(Properties ctx, Timestamp date, String trxName);
/** * * @param ol * @return {@code true} if there is at lease one term that references the given <code>ol</code> via its <code>C_OrderLine_Term_ID</code> column. */ boolean existsTermForOl(I_C_OrderLine ol); /** * Retrieves the terms that are connection to the given <code>olCand</code> via an active * <code>C_Contract_Term_Alloc</code> record. * * @param olCand * @return */ List<I_C_Flatrate_Term> retrieveTermsForOLCand(I_C_OLCand olCand); /** * Insert a new {@link I_C_SubscriptionProgress} after the given predecessor. All values from the predecessor are * copied to the new one, only <code>SeqNo</code> is set to the predecessor's <code>SeqNo+1</code>. The * <code>SeqNo</code>s of all existing {@link I_C_SubscriptionProgress} s that are already after * <code>predecessor</code> are increased by one. * * @param predecessor * @param trxName * @return */ I_C_SubscriptionProgress insertNewDelivery(I_C_SubscriptionProgress predecessor); <T extends I_C_OLCand> List<T> retrieveOLCands(I_C_Flatrate_Term term, Class<T> clazz); }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\ISubscriptionDAO.java
1
请完成以下Java代码
private DefaultView filterView( @NonNull final DefaultView view, @NonNull final JSONFilterViewRequest filterViewRequest) { final DocumentFilterDescriptorsProvider filterDescriptors = view.getViewDataRepository().getViewFilterDescriptors(); final DocumentFilterList newFilters = filterViewRequest.getFiltersUnwrapped(filterDescriptors); // final DocumentFilterList newFiltersExcludingFacets = newFilters.retainOnlyNonFacetFilters(); // // final DocumentFilterList currentFiltersExcludingFacets = view.getFilters().retainOnlyNonFacetFilters(); // // if (DocumentFilterList.equals(currentFiltersExcludingFacets, newFiltersExcludingFacets)) // { // // TODO // throw new AdempiereException("TODO"); // }
// else { return createView(CreateViewRequest.filterViewBuilder(view) .setFilters(newFilters) .build()); } } public SqlViewKeyColumnNamesMap getKeyColumnNamesMap(@NonNull final WindowId windowId) { final SqlViewBinding sqlBindings = viewLayouts.getViewBinding(windowId, DocumentFieldDescriptor.Characteristic.PublicField, ViewProfileId.NULL); return sqlBindings.getSqlViewKeyColumnNamesMap(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
static class PathPatternRequestMatcherBuilderConfiguration { @Bean @ConditionalOnMissingBean PathPatternRequestMatcher.Builder pathPatternRequestMatcherBuilder( DispatcherServletPath dispatcherServletPath) { PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults(); String path = dispatcherServletPath.getPath(); return (!path.equals("/")) ? builder.basePath(path) : builder; } } /** * The default configuration for web security. It relies on Spring Security's * content-negotiation strategy to determine what sort of authentication to use. If * the user specifies their own {@link SecurityFilterChain} bean, this will back-off * completely and the users should specify all the bits that they want to configure as * part of the custom security configuration. */ @Configuration(proxyBeanMethods = false) @ConditionalOnDefaultWebSecurity static class SecurityFilterChainConfiguration { @Bean @Order(SecurityFilterProperties.BASIC_AUTH_ORDER) SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) { http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated()); http.formLogin(withDefaults()); http.httpBasic(withDefaults()); return http.build(); } } /** * Adds the {@link EnableWebSecurity @EnableWebSecurity} annotation if Spring Security
* is on the classpath. This will make sure that the annotation is present with * default security auto-configuration and also if the user adds custom security and * forgets to add the annotation. If {@link EnableWebSecurity @EnableWebSecurity} has * already been added or if a bean with name * {@value BeanIds#SPRING_SECURITY_FILTER_CHAIN} has been configured by the user, this * will back-off. */ @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN) @ConditionalOnClass(EnableWebSecurity.class) @EnableWebSecurity static class EnableWebSecurityConfiguration { } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\web\servlet\ServletWebSecurityAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
private <C> Optional<C> getSharedOrBean(H http, Class<C> type) { C shared = http.getSharedObject(type); return Optional.ofNullable(shared).or(() -> getBeanOrNull(type)); } private <T> Optional<T> getBeanOrNull(Class<T> type) { ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return Optional.empty(); } try { return Optional.of(context.getBean(type)); } catch (NoSuchBeanDefinitionException ex) { return Optional.empty(); } } private MapUserCredentialRepository userCredentialRepository() { return new MapUserCredentialRepository();
} private PublicKeyCredentialUserEntityRepository userEntityRepository() { return new MapPublicKeyCredentialUserEntityRepository(); } private WebAuthnRelyingPartyOperations webAuthnRelyingPartyOperations( PublicKeyCredentialUserEntityRepository userEntities, UserCredentialRepository userCredentials) { Optional<WebAuthnRelyingPartyOperations> webauthnOperationsBean = getBeanOrNull( WebAuthnRelyingPartyOperations.class); String rpName = (this.rpName != null) ? this.rpName : this.rpId; return webauthnOperationsBean .orElseGet(() -> new Webauthn4JRelyingPartyOperations(userEntities, userCredentials, PublicKeyCredentialRpEntity.builder().id(this.rpId).name(rpName).build(), this.allowedOrigins)); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\WebAuthnConfigurer.java
2
请完成以下Java代码
public class HistoricCaseInstanceEntityManagerImpl extends AbstractEngineEntityManager<CmmnEngineConfiguration, HistoricCaseInstanceEntity, HistoricCaseInstanceDataManager> implements HistoricCaseInstanceEntityManager { public HistoricCaseInstanceEntityManagerImpl(CmmnEngineConfiguration cmmnEngineConfiguration, HistoricCaseInstanceDataManager historicCaseInstanceDataManager) { super(cmmnEngineConfiguration, historicCaseInstanceDataManager); } @Override public HistoricCaseInstanceEntity create(CaseInstance caseInstance) { return dataManager.create(caseInstance); } @Override public HistoricCaseInstanceQuery createHistoricCaseInstanceQuery() { return new HistoricCaseInstanceQueryImpl(engineConfiguration.getCommandExecutor(), engineConfiguration); } @Override public List<HistoricCaseInstanceEntity> findHistoricCaseInstancesByCaseDefinitionId(String caseDefinitionId) { return dataManager.findHistoricCaseInstancesByCaseDefinitionId(caseDefinitionId); } @Override public List<String> findHistoricCaseInstanceIdsByParentIds(Collection<String> caseInstanceIds) { return dataManager.findHistoricCaseInstanceIdsByParentIds(caseInstanceIds); } @Override public List<HistoricCaseInstance> findByCriteria(HistoricCaseInstanceQuery query) { return dataManager.findByCriteria((HistoricCaseInstanceQueryImpl) query); }
@Override @SuppressWarnings("unchecked") public List<HistoricCaseInstance> findWithVariablesByQueryCriteria(HistoricCaseInstanceQuery query) { return dataManager.findWithVariablesByQueryCriteria((HistoricCaseInstanceQueryImpl) query); } @Override public List<HistoricCaseInstance> findIdsByCriteria(HistoricCaseInstanceQuery query) { return dataManager.findIdsByCriteria((HistoricCaseInstanceQueryImpl) query); } @Override public long countByCriteria(HistoricCaseInstanceQuery query) { return dataManager.countByCriteria((HistoricCaseInstanceQueryImpl) query); } @Override public void deleteHistoricCaseInstances(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery) { dataManager.deleteHistoricCaseInstances(historicCaseInstanceQuery); } @Override public void bulkDeleteHistoricCaseInstances(Collection<String> caseInstanceIds) { dataManager.bulkDeleteHistoricCaseInstances(caseInstanceIds); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricCaseInstanceEntityManagerImpl.java
1
请完成以下Java代码
public void createC_InvoiceCandidate_InOutLines(final I_M_InOutLine inOutLine) { final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); // // Get Order Line final OrderLineId orderLineId = OrderLineId.ofRepoIdOrNull(inOutLine.getC_OrderLine_ID()); if (orderLineId == null) { return; // nothing to do } // // Iterate all invoice candidates linked to our order line // * create link between invoice candidate and our inout line for (final I_C_Invoice_Candidate icRecord : invoiceCandDAO.retrieveInvoiceCandidatesForOrderLineId(orderLineId)) { try (final MDCCloseable icRecordMDC = TableRecordMDC.putTableRecordReference(icRecord)) { final I_C_InvoiceCandidate_InOutLine iciol = InterfaceWrapperHelper.newInstance(I_C_InvoiceCandidate_InOutLine.class, inOutLine); iciol.setC_Invoice_Candidate(icRecord); invoiceCandBL.updateICIOLAssociationFromIOL(iciol, inOutLine); // TODO: QtyInvoiced shall be set! It's not so critical, atm is used on on Sales side (check call hierarchy of getQtyInvoiced()) // NOTE: when we will set it, because there can be more then one IC for one inoutLine we need to calculate this Qtys proportionally.
// // (also) calculate qualityDiscountPercent taken from inoutLines (06502) Services.get(IInvoiceCandidateHandlerBL.class).setDeliveredData(icRecord); final InvoiceCandidate invoiceCandidate = invoiceCandidateRecordService.ofRecord(icRecord); invoiceCandidateRecordService.updateRecord(invoiceCandidate, icRecord); InterfaceWrapperHelper.saveRecord(icRecord); } } // invalidate the candidates related to the inOutLine's order line..i'm not 100% if it's necessary, but we might need to e.g. update the // QtyDelivered or QtyPicked or whatever... // final I_C_OrderLine orderLine = Services.get(IOrderDAO.class).getOrderLineById(orderLineId); // Services.get(IInvoiceCandidateHandlerBL.class).invalidateCandidatesFor(orderLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\M_InOutLine.java
1
请完成以下Java代码
public LookupValuesPage getFilterParameterTypeahead(final String filterId, final String filterParameterName, final String query, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public DocumentFilterList getStickyFilters() { return DocumentFilterList.EMPTY; } @Override public DocumentFilterList getFilters() { return filters; } @Override public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); }
@Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO Auto-generated method stub } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } /** * @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}. */ @NonNull public ShipmentScheduleId getCurrentShipmentScheduleId() { return currentShipmentScheduleId; } @Override public void invalidateAll() { rows.invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java
1
请完成以下Java代码
public class WordCountingApp { public static void main(String[] args) throws InterruptedException { Logger.getLogger("org") .setLevel(Level.OFF); Logger.getLogger("akka") .setLevel(Level.OFF); Map<String, Object> kafkaParams = new HashMap<>(); kafkaParams.put("bootstrap.servers", "localhost:9092"); kafkaParams.put("key.deserializer", StringDeserializer.class); kafkaParams.put("value.deserializer", StringDeserializer.class); kafkaParams.put("group.id", "use_a_separate_group_id_for_each_stream"); kafkaParams.put("auto.offset.reset", "latest"); kafkaParams.put("enable.auto.commit", false); Collection<String> topics = Arrays.asList("messages"); SparkConf sparkConf = new SparkConf(); sparkConf.setMaster("local[2]"); sparkConf.setAppName("WordCountingApp"); sparkConf.set("spark.cassandra.connection.host", "127.0.0.1"); JavaStreamingContext streamingContext = new JavaStreamingContext(sparkConf, Durations.seconds(1)); JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams)); JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value())); JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+")) .iterator()); JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1)) .reduceByKey((i1, i2) -> i1 + i2); wordCounts.foreachRDD(javaRdd -> { Map<String, Integer> wordCountMap = javaRdd.collectAsMap(); for (String key : wordCountMap.keySet()) { List<Word> wordList = Arrays.asList(new Word(key, wordCountMap.get(key))); JavaRDD<Word> rdd = streamingContext.sparkContext() .parallelize(wordList); javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class)) .saveToCassandra(); } }); streamingContext.start(); streamingContext.awaitTermination(); } }
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\data\pipeline\WordCountingApp.java
1
请在Spring Boot框架中完成以下Java代码
public class CommissionInstanceService { private static final Logger logger = LogManager.getLogger(CommissionInstanceService.class); private final CommissionInstanceRequestFactory commissionInstanceRequestFactory; private final CommissionAlgorithmInvoker commissionAlgorithmInvoker; public CommissionInstanceService( @NonNull final CommissionInstanceRequestFactory commissionInstanceRequestFactory, @NonNull final CommissionAlgorithmInvoker commissionAlgorithmInvoker) { this.commissionInstanceRequestFactory = commissionInstanceRequestFactory; this.commissionAlgorithmInvoker = commissionAlgorithmInvoker; } public Optional<CommissionInstance> createCommissionInstance(@NonNull final CommissionTriggerDocument commissionTriggerDocument) { // request might be not present, if there are no matching contracts and/or settings final Optional<CreateCommissionSharesRequest> request = commissionInstanceRequestFactory.createRequestFor(commissionTriggerDocument); if (request.isPresent()) { final CommissionInstance result = CommissionInstance .builder() .currentTriggerData(request.get().getTrigger().getCommissionTriggerData()) .shares(commissionAlgorithmInvoker.createCommissionShares(request.get())) .build(); return Optional.of(result); } return Optional.empty(); } public void createAndAddMissingShares( @NonNull final CommissionInstance instance, @NonNull final CommissionTriggerDocument commissionTriggerDocument) { final Optional<CreateCommissionSharesRequest> request = commissionInstanceRequestFactory.createRequestFor(commissionTriggerDocument); if (!request.isPresent()) { return; } final Optional<HierarchyLevel> existingSharesHierarchyTopLevel = instance .getShares() .stream() .filter(share -> share.getLevel() != null) .map(CommissionShare::getLevel) .max(HierarchyLevel::compareTo); final HierarchyLevel startingHierarchyLevel = existingSharesHierarchyTopLevel.isPresent() ? existingSharesHierarchyTopLevel.get().incByOne()
: HierarchyLevel.ZERO; final ImmutableSet<CommissionConfig> existingConfigs = instance.getShares() .stream() .map(CommissionShare::getConfig) .collect(ImmutableSet.toImmutableSet()); final CreateCommissionSharesRequest sparsedOutRequest = request.get() .withoutConfigs(existingConfigs) .toBuilder() .startingHierarchyLevel(startingHierarchyLevel) .build(); if (sparsedOutRequest.getConfigs().isEmpty()) { logger.debug("There are no CommissionConfigs that were not already applied to the commission instance"); return; } final ImmutableList<CommissionShare> additionalShares = commissionAlgorithmInvoker.createCommissionShares(sparsedOutRequest); instance.addShares(additionalShares); logger.debug("Added {} additional salesCommissionShares to instance", additionalShares.size()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionInstanceService.java
2
请在Spring Boot框架中完成以下Java代码
public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "null") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } @ApiModelProperty(example = "active") public String getState() { return state; } public void setState(String state) { this.state = state; } @ApiModelProperty(example = "123") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case")
public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java
2
请完成以下Java代码
public void setDiscountDays (final int DiscountDays) { set_Value (COLUMNNAME_DiscountDays, DiscountDays); } @Override public int getDiscountDays() { return get_ValueAsInt(COLUMNNAME_DiscountDays); } @Override public void setEDI_cctop_140_v_ID (final int EDI_cctop_140_v_ID) { if (EDI_cctop_140_v_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_cctop_140_v_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_cctop_140_v_ID, EDI_cctop_140_v_ID); } @Override public int getEDI_cctop_140_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_140_v_ID); } @Override public de.metas.esb.edi.model.I_EDI_cctop_invoic_v getEDI_cctop_invoic_v() { return get_ValueAsPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class); } @Override public void setEDI_cctop_invoic_v(final de.metas.esb.edi.model.I_EDI_cctop_invoic_v EDI_cctop_invoic_v) { set_ValueFromPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class, EDI_cctop_invoic_v); } @Override public void setEDI_cctop_invoic_v_ID (final int EDI_cctop_invoic_v_ID) { if (EDI_cctop_invoic_v_ID < 1) set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null); else set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, EDI_cctop_invoic_v_ID); } @Override public int getEDI_cctop_invoic_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID); } @Override
public void setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_140_v.java
1
请完成以下Java代码
public Authentication authenticate(Authentication authentication) throws AuthenticationException { OAuth2ClientAuthenticationToken clientAuthentication = (OAuth2ClientAuthenticationToken) authentication; if (!ClientAuthenticationMethod.NONE.equals(clientAuthentication.getClientAuthenticationMethod())) { return null; } String clientId = clientAuthentication.getPrincipal().toString(); RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(clientId); if (registeredClient == null) { throwInvalidClient(OAuth2ParameterNames.CLIENT_ID); } if (this.logger.isTraceEnabled()) { this.logger.trace("Retrieved registered client"); } if (!registeredClient.getClientAuthenticationMethods() .contains(clientAuthentication.getClientAuthenticationMethod())) { throwInvalidClient("authentication_method"); } if (this.logger.isTraceEnabled()) { this.logger.trace("Validated client authentication parameters"); }
// Validate the "code_verifier" parameter for the public client this.codeVerifierAuthenticator.authenticateRequired(clientAuthentication, registeredClient); if (this.logger.isTraceEnabled()) { this.logger.trace("Authenticated public client"); } return new OAuth2ClientAuthenticationToken(registeredClient, clientAuthentication.getClientAuthenticationMethod(), null); } @Override public boolean supports(Class<?> authentication) { return OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication); } private static void throwInvalidClient(String parameterName) { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT, "Client authentication failed: " + parameterName, ERROR_URI); throw new OAuth2AuthenticationException(error); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\PublicClientAuthenticationProvider.java
1
请在Spring Boot框架中完成以下Java代码
public ClassLoader getClassLoader() { return this.classLoader; } public Xa getXa() { return this.xa; } public void setXa(Xa xa) { this.xa = xa; } /** * XA Specific datasource settings. */ public static class Xa { /** * XA datasource fully qualified name. */ private @Nullable String dataSourceClassName; /** * Properties to pass to the XA data source. */ private Map<String, String> properties = new LinkedHashMap<>(); public @Nullable String getDataSourceClassName() { return this.dataSourceClassName; } public void setDataSourceClassName(@Nullable String dataSourceClassName) { this.dataSourceClassName = dataSourceClassName; } public Map<String, String> getProperties() { return this.properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } } static class DataSourceBeanCreationException extends BeanCreationException {
private final DataSourceProperties properties; private final EmbeddedDatabaseConnection connection; DataSourceBeanCreationException(String message, DataSourceProperties properties, EmbeddedDatabaseConnection connection) { super(message); this.properties = properties; this.connection = connection; } DataSourceProperties getProperties() { return this.properties; } EmbeddedDatabaseConnection getConnection() { return this.connection; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceProperties.java
2
请完成以下Java代码
default String getSubject() { return this.getClaimAsString(IdTokenClaimNames.SUB); } /** * Returns the Audience(s) {@code (aud)} that this ID Token is intended for. * @return the Audience(s) that this ID Token is intended for */ default List<String> getAudience() { return this.getClaimAsStringList(IdTokenClaimNames.AUD); } /** * Returns the Expiration time {@code (exp)} on or after which the ID Token MUST NOT * be accepted. * @return the Expiration time on or after which the ID Token MUST NOT be accepted */ default Instant getExpiresAt() { return this.getClaimAsInstant(IdTokenClaimNames.EXP); } /** * Returns the time at which the ID Token was issued {@code (iat)}. * @return the time at which the ID Token was issued */ default Instant getIssuedAt() { return this.getClaimAsInstant(IdTokenClaimNames.IAT); } /** * Returns the time when the End-User authentication occurred {@code (auth_time)}. * @return the time when the End-User authentication occurred */ default Instant getAuthenticatedAt() { return this.getClaimAsInstant(IdTokenClaimNames.AUTH_TIME); } /** * Returns a {@code String} value {@code (nonce)} used to associate a Client session * with an ID Token, and to mitigate replay attacks. * @return the nonce used to associate a Client session with an ID Token */ default String getNonce() { return this.getClaimAsString(IdTokenClaimNames.NONCE); } /** * Returns the Authentication Context Class Reference {@code (acr)}. * @return the Authentication Context Class Reference */
default String getAuthenticationContextClass() { return this.getClaimAsString(IdTokenClaimNames.ACR); } /** * Returns the Authentication Methods References {@code (amr)}. * @return the Authentication Methods References */ default List<String> getAuthenticationMethods() { return this.getClaimAsStringList(IdTokenClaimNames.AMR); } /** * Returns the Authorized party {@code (azp)} to which the ID Token was issued. * @return the Authorized party to which the ID Token was issued */ default String getAuthorizedParty() { return this.getClaimAsString(IdTokenClaimNames.AZP); } /** * Returns the Access Token hash value {@code (at_hash)}. * @return the Access Token hash value */ default String getAccessTokenHash() { return this.getClaimAsString(IdTokenClaimNames.AT_HASH); } /** * Returns the Authorization Code hash value {@code (c_hash)}. * @return the Authorization Code hash value */ default String getAuthorizationCodeHash() { return this.getClaimAsString(IdTokenClaimNames.C_HASH); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\IdTokenClaimAccessor.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, Object> getTransientVariables() { return collectTransientVariables(new HashMap<>()); } protected Map<String, Object> collectTransientVariables(HashMap<String, Object> variables) { VariableScopeImpl parentScope = getParentVariableScope(); if (parentScope != null) { variables.putAll(parentScope.collectTransientVariables(variables)); } if (transientVariables != null) { for (String variableName : transientVariables.keySet()) { variables.put(variableName, transientVariables.get(variableName).getValue()); } } return variables; } @Override public void removeTransientVariableLocal(String variableName) { if (transientVariables != null) { transientVariables.remove(variableName); } } @Override public void removeTransientVariablesLocal() { if (transientVariables != null) { transientVariables.clear(); } } @Override public void removeTransientVariable(String variableName) { if (transientVariables != null && transientVariables.containsKey(variableName)) { removeTransientVariableLocal(variableName); return; } VariableScopeImpl parentVariableScope = getParentVariableScope(); if (parentVariableScope != null) { parentVariableScope.removeTransientVariable(variableName); } } @Override public void removeTransientVariables() { removeTransientVariablesLocal();
VariableScopeImpl parentVariableScope = getParentVariableScope(); if (parentVariableScope != null) { parentVariableScope.removeTransientVariablesLocal(); } } /** * Return whether changes to the variables are propagated to the history storage. */ protected abstract boolean isPropagateToHistoricVariable(); protected abstract VariableServiceConfiguration getVariableServiceConfiguration(); // getters and setters // ////////////////////////////////////////////////////// public ELContext getCachedElContext() { return cachedElContext; } public void setCachedElContext(ELContext cachedElContext) { this.cachedElContext = cachedElContext; } @Override public <T> T getVariable(String variableName, Class<T> variableClass) { return variableClass.cast(getVariable(variableName)); } @Override public <T> T getVariableLocal(String variableName, Class<T> variableClass) { return variableClass.cast(getVariableLocal(variableName)); } protected boolean isExpression(String variableName) { return variableName.startsWith("${") || variableName.startsWith("#{"); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\VariableScopeImpl.java
2
请完成以下Java代码
public int getSqlType() { return Types.ARRAY; } @Override public Class<Integer[]> returnedClass() { return Integer[].class; } @Override public boolean equals(Integer[] x, Integer[] y) { if (x instanceof Integer[] && y instanceof Integer[]) { return Arrays.deepEquals(x, y); } else { return false; } } @Override public int hashCode(Integer[] x) { return Arrays.hashCode(x); } @Override public Integer[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Array array = rs.getArray(position); return array != null ? (Integer[]) array.getArray() : null; } @Override public void nullSafeSet(PreparedStatement st, Integer[] value, int index, SharedSessionContractImplementor session) throws SQLException { if (st != null) { if (value != null) { Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("int", value); st.setArray(index, array); } else { st.setNull(index, Types.ARRAY);
} } } @Override public Integer[] deepCopy(Integer[] value) { return value != null ? Arrays.copyOf(value, value.length) : null; } @Override public boolean isMutable() { return false; } @Override public Serializable disassemble(Integer[] value) { return value; } @Override public Integer[] assemble(Serializable cached, Object owner) { return (Integer[]) cached; } @Override public Integer[] replace(Integer[] detached, Integer[] managed, Object owner) { return detached; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\arraymapping\CustomIntegerArrayType.java
1
请完成以下Java代码
public List<ITableRecordReference> getPath() { final List<ITableRecordReference> result = new ArrayList<>(); final AsUndirectedGraph<ITableRecordReference, DefaultEdge> undirectedGraph = new AsUndirectedGraph<>(g); final List<DefaultEdge> path = DijkstraShortestPath.<ITableRecordReference, DefaultEdge> findPathBetween( undirectedGraph, start, goal); if (path == null || path.isEmpty()) { return ImmutableList.of(); } result.add(start); for (final DefaultEdge e : path) { final ITableRecordReference edgeSource = undirectedGraph.getEdgeSource(e); if (!result.contains(edgeSource)) { result.add(edgeSource); } else {
result.add(undirectedGraph.getEdgeTarget(e)); } } return ImmutableList.copyOf(result); } /* package */ Graph<ITableRecordReference, DefaultEdge> getGraph() { return g; } @Override public String toString() { return "FindPathIterateResult [start=" + start + ", goal=" + goal + ", size=" + size + ", foundGoal=" + foundGoal + ", queueItemsToProcess.size()=" + queueItemsToProcess.size() + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\graph\FindPathIterateResult.java
1
请完成以下Java代码
protected PreparedStatement prepare(String query) { return preparedStatementMap.computeIfAbsent(query, i -> getSession().prepare(i)); } protected AsyncResultSet executeRead(TenantId tenantId, Statement statement) { return execute(tenantId, statement, defaultReadLevel, rateReadLimiter); } protected AsyncResultSet executeWrite(TenantId tenantId, Statement statement) { return execute(tenantId, statement, defaultWriteLevel, rateWriteLimiter); } protected TbResultSetFuture executeAsyncRead(TenantId tenantId, Statement statement) { return executeAsync(tenantId, statement, defaultReadLevel, rateReadLimiter); } protected TbResultSetFuture executeAsyncWrite(TenantId tenantId, Statement statement) { return executeAsync(tenantId, statement, defaultWriteLevel, rateWriteLimiter); } private AsyncResultSet execute(TenantId tenantId, Statement statement, ConsistencyLevel level, BufferedRateExecutor<CassandraStatementTask, TbResultSetFuture> rateExecutor) { if (log.isDebugEnabled()) { log.debug("Execute cassandra statement {}", statementToString(statement)); } return executeAsync(tenantId, statement, level, rateExecutor).getUninterruptibly(); } private TbResultSetFuture executeAsync(TenantId tenantId, Statement statement, ConsistencyLevel level, BufferedRateExecutor<CassandraStatementTask, TbResultSetFuture> rateExecutor) { if (log.isDebugEnabled()) {
log.debug("Execute cassandra async statement {}", statementToString(statement)); } if (statement.getConsistencyLevel() == null) { statement = statement.setConsistencyLevel(level); } return rateExecutor.submit(new CassandraStatementTask(tenantId, getSession(), statement)); } private static String statementToString(Statement statement) { if (statement instanceof BoundStatement) { return ((BoundStatement) statement).getPreparedStatement().getQuery(); } else { return statement.toString(); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\nosql\CassandraAbstractDao.java
1
请完成以下Java代码
public class RuleNodeStateEntity extends BaseSqlEntity<RuleNodeState> { @Column(name = ModelConstants.RULE_NODE_STATE_NODE_ID_PROPERTY) private UUID ruleNodeId; @Column(name = ModelConstants.RULE_NODE_STATE_ENTITY_TYPE_PROPERTY) private String entityType; @Column(name = ModelConstants.RULE_NODE_STATE_ENTITY_ID_PROPERTY) private UUID entityId; @Column(name = ModelConstants.RULE_NODE_STATE_DATA_PROPERTY) private String stateData; public RuleNodeStateEntity() { } public RuleNodeStateEntity(RuleNodeState ruleNodeState) { if (ruleNodeState.getId() != null) { this.setUuid(ruleNodeState.getUuidId()); } this.setCreatedTime(ruleNodeState.getCreatedTime());
this.ruleNodeId = DaoUtil.getId(ruleNodeState.getRuleNodeId()); this.entityId = ruleNodeState.getEntityId().getId(); this.entityType = ruleNodeState.getEntityId().getEntityType().name(); this.stateData = ruleNodeState.getStateData(); } @Override public RuleNodeState toData() { RuleNodeState ruleNode = new RuleNodeState(new RuleNodeStateId(this.getUuid())); ruleNode.setCreatedTime(createdTime); ruleNode.setRuleNodeId(new RuleNodeId(ruleNodeId)); ruleNode.setEntityId(EntityIdFactory.getByTypeAndUuid(entityType, entityId)); ruleNode.setStateData(stateData); return ruleNode; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\RuleNodeStateEntity.java
1
请完成以下Java代码
public void setSeqNo(String seqNo) { this.seqNo = seqNo; } public String getSeqNo() { return seqNo; } public BBANCodeEntryType getCodeType() { return codeType; } public void setCodeType(BBANCodeEntryType codeType) { this.codeType = codeType; } /**
* Basic Bank Account Number Entry Types. */ public enum BBANCodeEntryType { bank_code, branch_code, account_number, national_check_digit, account_type, owener_account_type, seqNo } public enum EntryCharacterType { n, // Digits (numeric characters 0 to 9 only) a, // Upper case letters (alphabetic characters A-Z only) c // upper and lower case alphanumeric characters (A-Z, a-z and 0-9) } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\wrapper\BBANStructureEntry.java
1
请完成以下Java代码
public static final CompositeDefaultViewProfileIdProvider of(final List<DefaultViewProfileIdProvider> providers) { return new CompositeDefaultViewProfileIdProvider(providers); } private final PlainDefaultViewProfileIdProvider overrides; private final ImmutableList<DefaultViewProfileIdProvider> providers; private final PlainDefaultViewProfileIdProvider fallback; private CompositeDefaultViewProfileIdProvider(final List<DefaultViewProfileIdProvider> providers) { overrides = new PlainDefaultViewProfileIdProvider(); fallback = new PlainDefaultViewProfileIdProvider(); this.providers = ImmutableList.<DefaultViewProfileIdProvider> builder() .add(overrides) .addAll(providers) .add(fallback) .build(); } @Override public ViewProfileId getDefaultProfileIdByWindowId(final WindowId windowId) { return providers.stream() .map(provider -> provider.getDefaultProfileIdByWindowId(windowId)) .filter(Objects::nonNull) .findFirst() .orElse(ViewProfileId.NULL); }
public void setDefaultProfileIdOverride(WindowId windowId, ViewProfileId profileId) { overrides.setDefaultProfileId(windowId, profileId); } public void setDefaultProfileIdFallback(WindowId windowId, ViewProfileId profileId) { fallback.setDefaultProfileId(windowId, profileId); } public void setDefaultProfileIdFallbackIfAbsent(WindowId windowId, ViewProfileId profileId) { fallback.setDefaultProfileIdIfAbsent(windowId, profileId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\CompositeDefaultViewProfileIdProvider.java
1
请完成以下Java代码
public void setSkipped_First_Time (final @Nullable java.sql.Timestamp Skipped_First_Time) { set_Value (COLUMNNAME_Skipped_First_Time, Skipped_First_Time); } @Override public java.sql.Timestamp getSkipped_First_Time() { return get_ValueAsTimestamp(COLUMNNAME_Skipped_First_Time); } @Override public void setSkipped_Last_Reason (final @Nullable java.lang.String Skipped_Last_Reason) { set_Value (COLUMNNAME_Skipped_Last_Reason, Skipped_Last_Reason); }
@Override public java.lang.String getSkipped_Last_Reason() { return get_ValueAsString(COLUMNNAME_Skipped_Last_Reason); } @Override public void setSkipTimeoutMillis (final int SkipTimeoutMillis) { set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis); } @Override public int getSkipTimeoutMillis() { return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage.java
1
请完成以下Java代码
public List<CardholderVerificationCapability1Code> getCrdhldrVrfctnCpblties() { if (crdhldrVrfctnCpblties == null) { crdhldrVrfctnCpblties = new ArrayList<CardholderVerificationCapability1Code>(); } return this.crdhldrVrfctnCpblties; } /** * Gets the value of the onLineCpblties property. * * @return * possible object is * {@link OnLineCapability1Code } * */ public OnLineCapability1Code getOnLineCpblties() { return onLineCpblties; } /** * Sets the value of the onLineCpblties property. * * @param value * allowed object is * {@link OnLineCapability1Code } * */ public void setOnLineCpblties(OnLineCapability1Code value) { this.onLineCpblties = value; } /** * Gets the value of the dispCpblties property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the dispCpblties property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDispCpblties().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DisplayCapabilities1 } * * */ public List<DisplayCapabilities1> getDispCpblties() { if (dispCpblties == null) { dispCpblties = new ArrayList<DisplayCapabilities1>(); } return this.dispCpblties; }
/** * Gets the value of the prtLineWidth property. * * @return * possible object is * {@link String } * */ public String getPrtLineWidth() { return prtLineWidth; } /** * Sets the value of the prtLineWidth property. * * @param value * allowed object is * {@link String } * */ public void setPrtLineWidth(String value) { this.prtLineWidth = 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\PointOfInteractionCapabilities1.java
1
请完成以下Spring Boot application配置
spring: application: name: mall-portal profiles: active: dev #默认为开发环境 mvc: pathmatch: matching-strategy: ant_path_matcher mybatis: mapper-locations: - classpath:dao/*.xml - classpath*:com/**/mapper/*.xml jwt: tokenHeader: Authorization #JWT存储的请求头 secret: mall-portal-secret #JWT加解密使用的密钥 expiration: 604800 #JWT的超期限时间(60*60*24*7) tokenHead: 'Bearer ' #JWT负载中拿到开头 secure: ignored: urls: #安全路径白名单 - /swagger-ui/ - /swagger-resources/** - /**/v2/api-docs - /**/*.html - /**/*.js - /**/*.css - /**/*.png - /**/*.map - /favicon.ico - /druid/** - /actuator/** - /sso/** - /home/** - /product/** - /brand/** - /alipay/**
# 自定义redis key redis: database: mall key: authCode: 'ums:authCode' orderId: 'oms:orderId' member: 'ums:member' expire: authCode: 90 # 验证码超期时间 common: 86400 # 24小时 mongo: insert: sqlEnable: true # 用于控制是否通过数据库数据来插入mongo # 消息队列定义 rabbitmq: queue: name: cancelOrder: cancelOrderQueue
repos\mall-master\mall-portal\src\main\resources\application.yml
2
请完成以下Java代码
protected JpaRepository<DomainEntity, UUID> getRepository() { return domainRepository; } @Override public PageData<Domain> findByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(domainRepository.findByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public int countDomainByTenantIdAndOauth2Enabled(TenantId tenantId, boolean enabled) { return domainRepository.countByTenantIdAndOauth2Enabled(tenantId.getId(), enabled); } @Override public List<DomainOauth2Client> findOauth2ClientsByDomainId(TenantId tenantId, DomainId domainId) { return DaoUtil.convertDataList(domainOauth2ClientRepository.findAllByDomainId(domainId.getId())); } @Override public void addOauth2Client(DomainOauth2Client domainOauth2Client) { domainOauth2ClientRepository.save(new DomainOauth2ClientEntity(domainOauth2Client)); }
@Override public void removeOauth2Client(DomainOauth2Client domainOauth2Client) { domainOauth2ClientRepository.deleteById(new DomainOauth2ClientCompositeKey(domainOauth2Client.getDomainId().getId(), domainOauth2Client.getOAuth2ClientId().getId())); } @Override public void deleteByTenantId(TenantId tenantId) { domainRepository.deleteByTenantId(tenantId.getId()); } @Override public EntityType getEntityType() { return EntityType.DOMAIN; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\domain\JpaDomainDao.java
1
请在Spring Boot框架中完成以下Java代码
public class HazardSymbolRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<Integer, HazardSymbolMap> cache = CCache.<Integer, HazardSymbolMap>builder() .tableName(I_M_HazardSymbol.Table_Name) .build(); public List<HazardSymbol> getByIds(@NonNull final Collection<HazardSymbolId> ids) { return getAll().getByIds(ids); } private HazardSymbolMap getAll() { return cache.getOrLoad(0, this::retrieveAll); } private HazardSymbolMap retrieveAll() { final ImmutableList<HazardSymbol> list = queryBL.createQueryBuilder(I_M_HazardSymbol.class) .addOnlyActiveRecordsFilter() .create() .stream()
.map(HazardSymbolRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new HazardSymbolMap(list); } private static HazardSymbol fromRecord(final I_M_HazardSymbol record) { final IModelTranslationMap trl = InterfaceWrapperHelper.getModelTranslationMap(record); return HazardSymbol.builder() .id(HazardSymbolId.ofRepoId(record.getM_HazardSymbol_ID())) .value(record.getValue()) .name(trl.getColumnTrl(I_M_HazardSymbol.COLUMNNAME_Name, record.getName())) .imageId(AdImageId.ofRepoIdOrNull(record.getAD_Image_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\hazard_symbol\HazardSymbolRepository.java
2
请完成以下Java代码
public class CardTransaction1Choice { @XmlElement(name = "Aggtd") protected CardAggregated1 aggtd; @XmlElement(name = "Indv") protected CardIndividualTransaction1 indv; /** * Gets the value of the aggtd property. * * @return * possible object is * {@link CardAggregated1 } * */ public CardAggregated1 getAggtd() { return aggtd; } /** * Sets the value of the aggtd property. * * @param value * allowed object is * {@link CardAggregated1 } * */ public void setAggtd(CardAggregated1 value) { this.aggtd = value; } /** * Gets the value of the indv property. * * @return * possible object is
* {@link CardIndividualTransaction1 } * */ public CardIndividualTransaction1 getIndv() { return indv; } /** * Sets the value of the indv property. * * @param value * allowed object is * {@link CardIndividualTransaction1 } * */ public void setIndv(CardIndividualTransaction1 value) { this.indv = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardTransaction1Choice.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<TbRuleEngineQueueConsumerManager> getConsumer(QueueKey queueKey) { return Optional.ofNullable(consumers.get(queueKey)); } private TbRuleEngineQueueConsumerManager createConsumer(QueueKey queueKey, Queue queue) { var consumer = TbRuleEngineQueueConsumerManager.create() .ctx(ctx) .queueKey(queueKey) .consumerExecutor(consumersExecutor) .scheduler(scheduler) .taskExecutor(mgmtExecutor) .build(); consumers.put(queueKey, consumer); consumer.init(queue); return consumer;
} private Optional<TbRuleEngineQueueConsumerManager> removeConsumer(QueueKey queueKey) { return Optional.ofNullable(consumers.remove(queueKey)); } @Scheduled(fixedDelayString = "${queue.rule-engine.stats.print-interval-ms}") public void printStats() { if (ctx.isStatsEnabled()) { long ts = System.currentTimeMillis(); consumers.values().forEach(manager -> manager.printStats(ts)); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbRuleEngineConsumerService.java
2
请完成以下Java代码
protected ExecutionEntity findFirstParentScopeExecution(ExecutionEntity executionEntity) { ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager(); ExecutionEntity parentScopeExecution = null; ExecutionEntity currentlyExaminedExecution = executionEntityManager.findById(executionEntity.getParentId()); while (currentlyExaminedExecution != null && parentScopeExecution == null) { if (currentlyExaminedExecution.isScope()) { parentScopeExecution = currentlyExaminedExecution; } else { currentlyExaminedExecution = executionEntityManager.findById(currentlyExaminedExecution.getParentId()); } } return parentScopeExecution; } public CommandContext getCommandContext() { return commandContext; } public void setCommandContext(CommandContext commandContext) { this.commandContext = commandContext; } public Agenda getAgenda() {
return agenda; } public void setAgenda(DefaultActivitiEngineAgenda agenda) { this.agenda = agenda; } public ExecutionEntity getExecution() { return execution; } public void setExecution(ExecutionEntity execution) { this.execution = execution; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\AbstractOperation.java
1
请完成以下Java代码
public final IHUIteratorListener.Result accept(final HUHolderType currentHUObj) { // In case our holder does not contain a proper HU, we shall continue searching if (currentHUObj == null) { return IHUIteratorListener.Result.CONTINUE; } if (isRootHUKey(currentHUObj)) { if (!isAggregatedHU(currentHUObj)) { // don't count current HU if it's not an aggregate HU return IHUIteratorListener.Result.CONTINUE; } incrementCounter(getAggregatedHUsCount(currentHUObj)); } else { if (isAggregatedHU(currentHUObj)) { incrementCounter(getAggregatedHUsCount(currentHUObj)); } else { if (!isCountVHUs() && isVirtualPI(currentHUObj)) { // skip virtual HUs; note that also aggregate HUs are "virtual", but that case is handled not here return IHUIteratorListener.Result.CONTINUE; } incrementCounter(1); } } // we are counting only first level => so skip downstream return IHUIteratorListener.Result.SKIP_DOWNSTREAM; } public final int getHUsCount() { return _counter;
} protected final boolean isCountVHUs() { return _countVHUs; } private final void incrementCounter(final int increment) { Check.assume(increment >= 0, "increment >= 0 but it was {}", increment); _counter += increment; } protected final boolean isRootHUKey(final HUHolderType huObj) { return huObj == _rootHUObj; } /** @return true if the HU is an aggregated HU */ protected abstract boolean isAggregatedHU(final HUHolderType huObj); /** * Called in case the HU is an aggregated HU and it shall return how many HUs are really contained. * * @return how many HUs are aggregated */ protected abstract int getAggregatedHUsCount(final HUHolderType huObj); /** @return true if the HU is a virtual one */ protected abstract boolean isVirtualPI(final HUHolderType huObj); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\AbstractIncludedHUsCounter.java
1
请完成以下Java代码
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { try { // // Evaluate the adLanguage parameter final OnVariableNotFound adLanguageOnVariableNoFound = getOnVariableNotFoundForInternalParameter(onVariableNotFound); final String adLanguage = StringExpressionsHelper.evaluateParam(adLanguageParam, ctx, adLanguageOnVariableNoFound); if (adLanguage == null || adLanguage == IStringExpression.EMPTY_RESULT) { return IStringExpression.EMPTY_RESULT; } else if (adLanguage.isEmpty() && onVariableNotFound == OnVariableNotFound.Empty) { return ""; } final IStringExpression expressionEffective; if (Language.isBaseLanguage(adLanguage)) { expressionEffective = expressionBaseLang; } else { expressionEffective = expressionTrl; } return expressionEffective.evaluate(ctx, onVariableNotFound); } catch (final Exception e) { throw ExpressionEvaluationException.wrapIfNeeded(e) .addExpression(this); } } private static final OnVariableNotFound getOnVariableNotFoundForInternalParameter(final OnVariableNotFound onVariableNotFound) { switch (onVariableNotFound) { case Preserve: // Preserve is not supported because we don't know which expression to pick if the deciding parameter is not determined return OnVariableNotFound.Fail; default: return onVariableNotFound; } } @Override public IStringExpression resolvePartial(final Evaluatee ctx)
{ try { boolean changed = false; final IStringExpression expressionBaseLangNew = expressionBaseLang.resolvePartial(ctx); if (!expressionBaseLang.equals(expressionBaseLangNew)) { changed = true; } final IStringExpression expressionTrlNew = expressionTrl.resolvePartial(Evaluatees.excludingVariables(ctx, adLanguageParam.getName())); if (!changed && !expressionTrl.equals(expressionTrlNew)) { changed = true; } if (!changed) { return this; } return new TranslatableParameterizedStringExpression(adLanguageParam, expressionBaseLangNew, expressionTrlNew); } catch (final Exception e) { throw ExpressionEvaluationException.wrapIfNeeded(e) .addExpression(this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\TranslatableParameterizedStringExpression.java
1
请在Spring Boot框架中完成以下Java代码
public class ApiController { @Resource UserDao userDao; // 查询一条记录 @RequestMapping(value = "/users/{id}", method = RequestMethod.GET) @ResponseBody public Result<User> getOne(@PathVariable("id") Integer id) { if (id == null || id < 1) { return ResultGenerator.genFailResult("缺少参数"); } User user = userDao.getUserById(id); if (user == null) { return ResultGenerator.genFailResult("无此数据"); } return ResultGenerator.genSuccessResult(user); } // 查询所有记录 @RequestMapping(value = "/users", method = RequestMethod.GET) @ResponseBody public Result<List<User>> queryAll() { List<User> users = userDao.findAllUsers(); return ResultGenerator.genSuccessResult(users); } // 新增一条记录 @RequestMapping(value = "/users", method = RequestMethod.POST) @ResponseBody public Result<Boolean> insert(@RequestBody User user) { // 参数验证 if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())) { return ResultGenerator.genFailResult("缺少参数"); } return ResultGenerator.genSuccessResult(userDao.insertUser(user) > 0); } // 修改一条记录
@RequestMapping(value = "/users", method = RequestMethod.PUT) @ResponseBody public Result<Boolean> update(@RequestBody User tempUser) { //参数验证 if (tempUser.getId() == null || tempUser.getId() < 1 || StringUtils.isEmpty(tempUser.getName()) || StringUtils.isEmpty(tempUser.getPassword())) { return ResultGenerator.genFailResult("缺少参数"); } //实体验证,不存在则不继续修改操作 User user = userDao.getUserById(tempUser.getId()); if (user == null) { return ResultGenerator.genFailResult("参数异常"); } user.setName(tempUser.getName()); user.setPassword(tempUser.getPassword()); return ResultGenerator.genSuccessResult(userDao.updUser(user) > 0); } // 删除一条记录 @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE) @ResponseBody public Result<Boolean> delete(@PathVariable("id") Integer id) { if (id == null || id < 1) { return ResultGenerator.genFailResult("缺少参数"); } return ResultGenerator.genSuccessResult(userDao.delUser(id) > 0); } }
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-RESTful-api\src\main\java\cn\lanqiao\springboot3\controller\ApiController.java
2
请完成以下Java代码
default CurrencyConversionResult convert( @NonNull final CurrencyConversionContext conversionCtx, @NonNull final Money amt, @NonNull final CurrencyId currencyToId) { return convert(conversionCtx, amt.toBigDecimal(), amt.getCurrencyId(), currencyToId); } Optional<CurrencyRate> getCurrencyRateIfExists( @NonNull CurrencyId currencyFromId, @NonNull CurrencyId currencyToId, @NonNull Instant convDate, @Nullable CurrencyConversionTypeId conversionTypeId, @NonNull ClientId clientId, @NonNull OrgId orgId); CurrencyConversionTypeId getCurrencyConversionTypeId(@NonNull ConversionTypeMethod type); CurrencyRate getCurrencyRate( @NonNull CurrencyId currencyFromId, @NonNull CurrencyId currencyToId, @NonNull Instant convDate, @Nullable CurrencyConversionTypeId conversionTypeId, @NonNull ClientId clientId, @NonNull OrgId orgId); @NonNull CurrencyRate getCurrencyRate( CurrencyConversionContext conversionCtx, CurrencyId currencyFromId, CurrencyId currencyToId) throws NoCurrencyRateFoundException;
@NonNull CurrencyCode getCurrencyCodeById(@NonNull CurrencyId currencyId); @NonNull Currency getByCurrencyCode(@NonNull CurrencyCode currencyCode); @NonNull Money convertToBase(@NonNull CurrencyConversionContext conversionCtx, @NonNull Money amt); CurrencyPrecision getStdPrecision(CurrencyId currencyId); CurrencyPrecision getCostingPrecision(CurrencyId currencyId); @NonNull CurrencyConversionTypeId getCurrencyConversionTypeIdOrDefault(@NonNull OrgId orgId, @Nullable String conversionTypeName); Money convert( @NonNull Money amount, @NonNull CurrencyId toCurrencyId, @NonNull LocalDate conversionDate, @NonNull ClientAndOrgId clientAndOrgId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\ICurrencyBL.java
1
请完成以下Java代码
public java.lang.String getRestApiBaseURL () { return (java.lang.String)get_Value(COLUMNNAME_RestApiBaseURL); } /** Set Creditpass-Prüfung wiederholen . @param RetryAfterDays Creditpass-Prüfung wiederholen */ @Override public void setRetryAfterDays (java.math.BigDecimal RetryAfterDays) { set_Value (COLUMNNAME_RetryAfterDays, RetryAfterDays); } /** Get Creditpass-Prüfung wiederholen . @return Creditpass-Prüfung wiederholen */ @Override public java.math.BigDecimal getRetryAfterDays () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RetryAfterDays); if (bd == null) return BigDecimal.ZERO; return bd; } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config.java
1
请完成以下Java代码
protected void addInitiatorCanCompleteExtensionElement(boolean canCompleteTask, UserTask task) { addExtensionElement("initiator-can-complete", String.valueOf(canCompleteTask), task); } protected void addExtensionElement(String name, JsonNode elementNode, UserTask task) { if (elementNode != null && !elementNode.isNull() && StringUtils.isNotEmpty(elementNode.asText())) { addExtensionElement(name, elementNode.asText(), task); } } protected void addExtensionElement(String name, String elementText, UserTask task) { ExtensionElement extensionElement = new ExtensionElement(); extensionElement.setNamespace(NAMESPACE); extensionElement.setNamespacePrefix("modeler"); extensionElement.setName(name); extensionElement.setElementText(elementText); task.addExtensionElement(extensionElement); } protected void fillProperty( String propertyName, String extensionElementName, ObjectNode elementNode,
UserTask task ) { List<ExtensionElement> extensionElementList = task.getExtensionElements().get(extensionElementName); if (CollectionUtils.isNotEmpty(extensionElementList)) { elementNode.put(propertyName, extensionElementList.get(0).getElementText()); } } @Override public void setFormMap(Map<String, String> formMap) { this.formMap = formMap; } @Override public void setFormKeyMap(Map<String, ModelInfo> formKeyMap) { this.formKeyMap = formKeyMap; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\UserTaskJsonConverter.java
1
请完成以下Java代码
public boolean isAP() {return isPurchase();} public boolean isCustomerInvoice() { return this == CustomerInvoice; } public boolean isCustomerCreditMemo() { return this == CustomerCreditMemo; } public boolean isVendorCreditMemo() { return this == VendorCreditMemo;
} public boolean isIncomingCash() { return (isSales() && !isCreditMemo()) // ARI || (isPurchase() && isCreditMemo()) // APC ; } public boolean isOutgoingCash() { return !isIncomingCash(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceDocBaseType.java
1
请完成以下Java代码
public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! return projectPath + "/" + currentModulesPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判断自定义文件夹是否需要创建 checkDir("调用默认方法创建的目录"); return false; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig);
// 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); // 写于父类中的公共字段 strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
repos\spring-boot-quick-master\quick-mybatis-druid\src\main\java\com\quick\druid\utils\CodeGenerator.java
1
请完成以下Java代码
class Response { private final boolean allowed; private final long tokensRemaining; private final Map<String, String> headers; public Response(boolean allowed, Map<String, String> headers) { this.allowed = allowed; this.tokensRemaining = -1; Objects.requireNonNull(headers, "headers may not be null"); this.headers = headers; } public boolean isAllowed() { return allowed; }
public Map<String, String> getHeaders() { return Collections.unmodifiableMap(headers); } @Override public String toString() { final StringBuffer sb = new StringBuffer("Response{"); sb.append("allowed=").append(allowed); sb.append(", headers=").append(headers); sb.append(", tokensRemaining=").append(tokensRemaining); sb.append('}'); return sb.toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\ratelimit\RateLimiter.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final PInstanceId productsSelectionId = createProductsSelection(); final Instant startDate = getStartDate(); getCostElements().forEach(costElement -> recomputeCosts(costElement, productsSelectionId, startDate)); return MSG_OK; } private PInstanceId createProductsSelection() { final Set<ProductId> productIds = inventoryDAO.retrieveUsedProductsByInventoryIds(getSelectedInventoryIds()); if (productIds.isEmpty()) { throw new AdempiereException("No Products"); } return DB.createT_Selection(productIds, ITrx.TRXNAME_ThreadInherited); } private Set<InventoryId> getSelectedInventoryIds() { return retrieveSelectedRecordsQueryBuilder(I_M_Inventory.class) .create() .listIds() .stream() .map(InventoryId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); }
private void recomputeCosts( @NonNull final CostElement costElement, @NonNull final PInstanceId productsSelectionId, @NonNull final Instant startDate) { DB.executeFunctionCallEx(getTrxName() , "select \"de_metas_acct\".product_costs_recreate_from_date( p_C_AcctSchema_ID :=" + getAccountingSchemaId().getRepoId() + ", p_M_CostElement_ID:=" + costElement.getId().getRepoId() + ", p_m_product_selection_id:=" + productsSelectionId.getRepoId() + " , p_ReorderDocs_DateAcct_Trunc:='MM'" + ", p_StartDateAcct:=" + DB.TO_SQL(startDate) + "::date)" // , null // ); } private Instant getStartDate() { return inventoryDAO.getMinInventoryDate(getSelectedInventoryIds()) .orElseThrow(() -> new AdempiereException("Cannot determine Start Date")); } private List<CostElement> getCostElements() { if (p_costingMethod != null) { return costElementRepository.getMaterialCostingElementsForCostingMethod(p_costingMethod); } return costElementRepository.getActiveMaterialCostingElements(getClientID()); } private AcctSchemaId getAccountingSchemaId() {return p_C_AcctSchema_ID;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\process\M_Inventory_RecomputeCosts.java
1
请完成以下Java代码
public static MHREmployee getActiveEmployee(Properties ctx, int C_BPartner_ID, String trxName) { return new Query(ctx, Table_Name, COLUMNNAME_C_BPartner_ID+"=?", trxName) .setOnlyActiveRecords(true) .setParameters(new Object[]{C_BPartner_ID}) .setOrderBy(COLUMNNAME_HR_Employee_ID+" DESC") // just in case... .first(); } /** Cache */ private static CCache<Integer, MHREmployee> s_cache = new CCache<>(Table_Name, 1000); /************************************************************************** * Invoice Line Constructor * @param ctx context * @param HR_Employee_ID ID Employee * @param trxName transaction name */ public MHREmployee (Properties ctx, int HR_Employee_ID, String trxName) //-- {
super (ctx, HR_Employee_ID, trxName); if (HR_Employee_ID == 0) { setClientOrg(Env.getAD_Client_ID(Env.getCtx()), Env.getAD_Org_ID(Env.getCtx())); } } // MHREmployee /** * Load Constructor * @param ctx context * @param rs result set record */ public MHREmployee (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MHREmployee } // MHREmployee
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHREmployee.java
1
请在Spring Boot框架中完成以下Java代码
public IdentityService getIdentityService() { return processEngine.getIdentityService(); } @Bean(name = "managementService") @Override public ManagementService getManagementService() { return processEngine.getManagementService(); } @Bean(name = "authorizationService") @Override public AuthorizationService getAuthorizationService() { return processEngine.getAuthorizationService(); } @Bean(name = "caseService") @Override public CaseService getCaseService() { return processEngine.getCaseService(); } @Bean(name = "filterService") @Override public FilterService getFilterService() {
return processEngine.getFilterService(); } @Bean(name = "externalTaskService") @Override public ExternalTaskService getExternalTaskService() { return processEngine.getExternalTaskService(); } @Bean(name = "decisionService") @Override public DecisionService getDecisionService() { return processEngine.getDecisionService(); } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringProcessEngineServicesConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class LotteryConfiguration { private static final Logger LOG = LoggerFactory.getLogger(LotteryConfiguration.class); @Value("${lottery.contract.owner-address}") private String ownerAddress; @Value("${web3j.client-address}") private String clientAddress; @Autowired private LotteryProperties config; @Bean public Web3j web3j() { return Web3j.build(new HttpService(clientAddress, new OkHttpClient.Builder().build())); } @Bean public LotteryService contract(Web3j web3j, @Value("${lottery.contract.address:}") String contractAddress) throws Exception { if (StringUtils.isEmpty(contractAddress)) {
Lottery lottery = deployContract(web3j); return initLotteryService(lottery.getContractAddress(), web3j); } return initLotteryService(contractAddress, web3j); } private LotteryService initLotteryService(String contractAddress, Web3j web3j) { return new LotteryService(contractAddress, web3j, config); } private Lottery deployContract(Web3j web3j) throws Exception { LOG.info("About to deploy new contract..."); Lottery contract = Lottery.deploy(web3j, txManager(web3j), config.gas()).send(); LOG.info("Deployed new contract with address '{}'", contract.getContractAddress()); return contract; } private TransactionManager txManager(Web3j web3j) { return new ClientTransactionManager(web3j, ownerAddress); } }
repos\springboot-demo-master\Blockchain\src\main\java\com\et\bc\config\LotteryConfiguration.java
2
请完成以下Java代码
private abstract static class Mapping { private final String prefix; Mapping(String prefix) { this.prefix = prefix; } String getPrefix() { return this.prefix; } abstract @Nullable AnsiElement getElement(String postfix); } /** * {@link Mapping} for {@link AnsiElement} enums. */ private static class EnumMapping<E extends Enum<E> & AnsiElement> extends Mapping { private final Set<E> enums; EnumMapping(String prefix, Class<E> enumType) { super(prefix); this.enums = EnumSet.allOf(enumType); } @Override @Nullable AnsiElement getElement(String postfix) { for (Enum<?> candidate : this.enums) { if (candidate.name().equals(postfix)) { return (AnsiElement) candidate; } } return null; } } /** * {@link Mapping} for {@link Ansi8BitColor}. */ private static class Ansi8BitColorMapping extends Mapping { private final IntFunction<Ansi8BitColor> factory;
Ansi8BitColorMapping(String prefix, IntFunction<Ansi8BitColor> factory) { super(prefix); this.factory = factory; } @Override @Nullable AnsiElement getElement(String postfix) { if (containsOnlyDigits(postfix)) { try { return this.factory.apply(Integer.parseInt(postfix)); } catch (IllegalArgumentException ex) { // Ignore } } return null; } private boolean containsOnlyDigits(String postfix) { for (int i = 0; i < postfix.length(); i++) { if (!Character.isDigit(postfix.charAt(i))) { return false; } } return !postfix.isEmpty(); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ansi\AnsiPropertySource.java
1
请完成以下Java代码
public class CmmnDiExtensionXmlConverter extends BaseCmmnXmlConverter { protected static final Logger LOGGER = LoggerFactory.getLogger(CmmnDiExtensionXmlConverter.class); @Override public String getXMLElementName() { return CmmnXmlConstants.ELEMENT_DI_EXTENSION; } @Override public boolean hasChildElements() { return false; } @Override protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { CmmnDiEdge edgeInfo = conversionHelper.getCurrentDiEdge(); if (edgeInfo == null) { return null; } boolean readyWithChildElements = false; try { while (!readyWithChildElements && xtr.hasNext()) { xtr.next(); if (xtr.isStartElement()) { if (CmmnXmlConstants.ELEMENT_DI_DOCKER.equals(xtr.getLocalName())) { String type = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_TYPE); if ("source".equals(type) || "target".equals(type)) { GraphicInfo graphicInfo = new GraphicInfo(); graphicInfo.setX(Double.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_X))); graphicInfo.setY(Double.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_Y))); if ("source".equals(type)) { edgeInfo.setSourceDockerInfo(graphicInfo); } else { edgeInfo.setTargetDockerInfo(graphicInfo); }
} } } else if (xtr.isEndElement()) { if (CmmnXmlConstants.ELEMENT_DI_EXTENSION.equalsIgnoreCase(xtr.getLocalName())) { readyWithChildElements = true; } } } } catch (Exception ex) { LOGGER.error("Error processing CMMN document", ex); throw new XMLException("Error processing CMMN document", ex); } return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\CmmnDiExtensionXmlConverter.java
1
请完成以下Java代码
protected void sendCancelEvent(TimerJobEntity jobToDelete) { if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_CANCELED, jobToDelete)); } } protected TimerJobEntity getJobToDelete(CommandContext commandContext) { if (timerJobId == null) { throw new ActivitiIllegalArgumentException("jobId is null"); } if (log.isDebugEnabled()) { log.debug("Deleting job {}", timerJobId); }
TimerJobEntity job = commandContext.getTimerJobEntityManager().findById(timerJobId); if (job == null) { throw new ActivitiObjectNotFoundException("No timer job found with id '" + timerJobId + "'", Job.class); } // We need to check if the job was locked, ie acquired by the job acquisition thread // This happens if the job was already acquired, but not yet executed. // In that case, we can't allow to delete the job. if (job.getLockOwner() != null) { throw new ActivitiException("Cannot delete timer job when the job is being executed. Try again later."); } return job; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteTimerJobCmd.java
1
请完成以下Java代码
public String getLocalizedName() { return localizedName; } @Override public void setLocalizedName(String localizedName) { this.localizedName = localizedName; } @Override public String getDescription() { if (localizedDescription != null && localizedDescription.length() > 0) { return localizedDescription; } else { return description; } } public void setDescription(String description) { this.description = description; } public String getLocalizedDescription() { return localizedDescription; } @Override public void setLocalizedDescription(String localizedDescription) { this.localizedDescription = localizedDescription; } @Override public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } }
} return variables; } public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "HistoricProcessInstanceEntity[superProcessInstanceId=" + superProcessInstanceId + "]"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntity.java
1
请在Spring Boot框架中完成以下Java代码
private void checkParam(RegisterReq registerReq) { // 密码不能为空 if (StringUtils.isEmpty(registerReq.getPassword())) { throw new CommonBizException(ExpCodeEnum.PASSWD_NULL); } // 手机号不能为空 if (StringUtils.isEmpty(registerReq.getPhone())) { throw new CommonBizException(ExpCodeEnum.PHONE_NULL); } // mail不能为空 if (StringUtils.isEmpty(registerReq.getMail())) { throw new CommonBizException(ExpCodeEnum.MAIL_NULL); } // 用户类别不能为空 if (registerReq.getUserType() == null) { throw new CommonBizException(ExpCodeEnum.USERTYPE_NULL); } // 企业用户 if (registerReq.getUserType() == UserTypeEnum.Company.getCode()) { // 营业执照不能为空 if (StringUtils.isEmpty(registerReq.getLicencePic())) { throw new CommonBizException(ExpCodeEnum.LICENCE_NULL); } // 企业名称不能为空 if (StringUtils.isEmpty(registerReq.getUsername())) { throw new CommonBizException(ExpCodeEnum.COMPANYNAME_NULL);
} } } /** * 参数校验 * @param loginReq */ private void checkParam(LoginReq loginReq) { // 密码不能为空 if (StringUtils.isEmpty(loginReq.getPassword())) { throw new CommonBizException(ExpCodeEnum.PASSWD_NULL); } // 手机、mail、用户名 至少填一个 if (StringUtils.isEmpty(loginReq.getUsername()) && StringUtils.isEmpty(loginReq.getMail()) && StringUtils.isEmpty(loginReq.getPhone())) { throw new CommonBizException(ExpCodeEnum.AUTH_NULL); } } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-User\src\main\java\com\gaoxi\user\service\UserServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Duration getConnect() { return this.connect; } public void setConnect(Duration connect) { this.connect = connect; } public Duration getDisconnect() { return this.disconnect; } public void setDisconnect(Duration disconnect) { this.disconnect = disconnect; } public Duration getKeyValue() { return this.keyValue; } public void setKeyValue(Duration keyValue) { this.keyValue = keyValue; } public Duration getKeyValueDurable() { return this.keyValueDurable; } public void setKeyValueDurable(Duration keyValueDurable) { this.keyValueDurable = keyValueDurable; } public Duration getQuery() { return this.query; } public void setQuery(Duration query) { this.query = query; } public Duration getView() { return this.view; }
public void setView(Duration view) { this.view = view; } public Duration getSearch() { return this.search; } public void setSearch(Duration search) { this.search = search; } public Duration getAnalytics() { return this.analytics; } public void setAnalytics(Duration analytics) { this.analytics = analytics; } public Duration getManagement() { return this.management; } public void setManagement(Duration management) { this.management = management; } } }
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseProperties.java
2
请在Spring Boot框架中完成以下Java代码
public static DemandDetailsQuery ofDemandDetail(@NonNull final DemandDetail demandDetail) { return new DemandDetailsQuery( toUnspecifiedIfZero(demandDetail.getShipmentScheduleId()), toUnspecifiedIfZero(demandDetail.getOrderLineId()), toUnspecifiedIfZero(demandDetail.getSubscriptionProgressId()), toUnspecifiedIfZero(demandDetail.getForecastLineId()), toUnspecifiedIfZero(demandDetail.getInOutLineId())); } public static DemandDetailsQuery ofSupplyRequiredDescriptor(@NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor) { return ofDemandDetail(DemandDetail.forSupplyRequiredDescriptor(supplyRequiredDescriptor)); } public static DemandDetailsQuery forDocumentLine( @NonNull final DocumentLineDescriptor documentLineDescriptor) { if (documentLineDescriptor instanceof OrderLineDescriptor) { final OrderLineDescriptor orderLineDescriptor = OrderLineDescriptor.cast(documentLineDescriptor); return new DemandDetailsQuery( UNSPECIFIED_REPO_ID, orderLineDescriptor.getOrderLineId(), UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID); } else if (documentLineDescriptor instanceof SubscriptionLineDescriptor) { final SubscriptionLineDescriptor subscriptionLineDescriptor = SubscriptionLineDescriptor.cast(documentLineDescriptor); return new DemandDetailsQuery( UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, subscriptionLineDescriptor.getSubscriptionProgressId(), UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID); } else { //noinspection ThrowableNotThrown Check.fail("documentLineDescriptor has unsupported type={}; documentLineDescriptor={}", documentLineDescriptor.getClass(), documentLineDescriptor); } return null; } public static DemandDetailsQuery ofShipmentLineId(final int inOutLineId) { Check.assumeGreaterThanZero(inOutLineId, "inOutLineId"); return new DemandDetailsQuery( UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, inOutLineId); } int shipmentScheduleId;
int orderLineId; int subscriptionLineId; int forecastLineId; int inOutLineId; private DemandDetailsQuery( final int shipmentScheduleId, final int orderLineId, final int subscriptionLineId, final int forecastLineId, final int inOutLineId) { this.shipmentScheduleId = shipmentScheduleId; this.orderLineId = orderLineId; this.subscriptionLineId = subscriptionLineId; this.forecastLineId = forecastLineId; this.inOutLineId = inOutLineId; IdConstants.assertValidId(shipmentScheduleId, "shipmentScheduleId"); IdConstants.assertValidId(orderLineId, "orderLineId"); IdConstants.assertValidId(subscriptionLineId, "subscriptionLineId"); IdConstants.assertValidId(forecastLineId, "forecastLineId"); IdConstants.assertValidId(inOutLineId, "inOutLineId"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\query\DemandDetailsQuery.java
2
请完成以下Java代码
public ESRImportEnqueuer fromDataSource(final ESRImportEnqueuerDataSource fromDataSource) { this.fromDataSource = fromDataSource; return this; } @NonNull private ESRImportEnqueuerDataSource getFromDataSource() { return fromDataSource; } public ESRImportEnqueuer loggable(@NonNull final ILoggable loggable) { this.loggable = loggable; return this; } private void addLog(final String msg, final Object... msgParameters) { loggable.addLog(msg, msgParameters); } private static class ZipFileResource extends AbstractResource { private final byte[] data; private final String filename; @Builder private ZipFileResource( @NonNull final byte[] data, @NonNull final String filename) { this.data = data; this.filename = filename;
} @Override public String getFilename() { return filename; } @Override public String getDescription() { return null; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(data); } public byte[] getData() { return data; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\ESRImportEnqueuer.java
1
请在Spring Boot框架中完成以下Java代码
public boolean enabled() { return obtain(GraphiteProperties::isEnabled, GraphiteConfig.super::enabled); } @Override public Duration step() { return obtain(GraphiteProperties::getStep, GraphiteConfig.super::step); } @Override public TimeUnit rateUnits() { return obtain(GraphiteProperties::getRateUnits, GraphiteConfig.super::rateUnits); } @Override public TimeUnit durationUnits() { return obtain(GraphiteProperties::getDurationUnits, GraphiteConfig.super::durationUnits); } @Override public String host() { return obtain(GraphiteProperties::getHost, GraphiteConfig.super::host); } @Override public int port() { return obtain(GraphiteProperties::getPort, GraphiteConfig.super::port); } @Override
public GraphiteProtocol protocol() { return obtain(GraphiteProperties::getProtocol, GraphiteConfig.super::protocol); } @Override public boolean graphiteTagsEnabled() { return obtain(GraphiteProperties::getGraphiteTagsEnabled, GraphiteConfig.super::graphiteTagsEnabled); } @Override public String[] tagsAsPrefix() { return obtain(GraphiteProperties::getTagsAsPrefix, GraphiteConfig.super::tagsAsPrefix); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\graphite\GraphitePropertiesConfigAdapter.java
2
请完成以下Java代码
public static Optional<HUPIAttributeId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final HUPIAttributeId id) { return id != null ? id.getRepoId() : -1; } int repoId; private HUPIAttributeId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Attribute_ID");
} @JsonValue @Override public int getRepoId() { return repoId; } public static boolean equals(@Nullable final HUPIAttributeId id1, @Nullable final HUPIAttributeId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HUPIAttributeId.java
1
请完成以下Java代码
public class YieldedOrValueType1Choice { @XmlElement(name = "Yldd") protected Boolean yldd; @XmlElement(name = "ValTp") @XmlSchemaType(name = "string") protected PriceValueType1Code valTp; /** * Gets the value of the yldd property. * * @return * possible object is * {@link Boolean } * */ public Boolean isYldd() { return yldd; } /** * Sets the value of the yldd property. * * @param value * allowed object is * {@link Boolean } * */ public void setYldd(Boolean value) { this.yldd = value; } /** * Gets the value of the valTp property. * * @return
* possible object is * {@link PriceValueType1Code } * */ public PriceValueType1Code getValTp() { return valTp; } /** * Sets the value of the valTp property. * * @param value * allowed object is * {@link PriceValueType1Code } * */ public void setValTp(PriceValueType1Code value) { this.valTp = 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\YieldedOrValueType1Choice.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getNamespacePrefix() { return namespacePrefix; } public void setNamespacePrefix(String namespacePrefix) { this.namespacePrefix = namespacePrefix; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); if (namespacePrefix != null) { sb.append(namespacePrefix); if (name != null) sb.append(":").append(name); } else sb.append(name); if (value != null) sb.append("=").append(value); return sb.toString(); } public ExtensionAttribute clone() { ExtensionAttribute clone = new ExtensionAttribute(); clone.setValues(this); return clone; } public void setValues(ExtensionAttribute otherAttribute) { setName(otherAttribute.getName()); setValue(otherAttribute.getValue()); setNamespacePrefix(otherAttribute.getNamespacePrefix()); setNamespace(otherAttribute.getNamespace()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ExtensionAttribute.java
1
请完成以下Java代码
public class ProcessEngineException extends RuntimeException { private static final long serialVersionUID = 1L; protected int code = BuiltinExceptionCode.FALLBACK.getCode(); public ProcessEngineException() { super(); } public ProcessEngineException(String message, Throwable cause) { super(message, cause); } public ProcessEngineException(String message) { super(message); } public ProcessEngineException(String message, int code) { super(message); this.code = code; } public ProcessEngineException(Throwable cause) { super(cause); } /** * <p>The exception code can be set via delegation code. * * <p>Setting an error code on the exception in delegation code always overrides
* the exception code from a custom {@link ExceptionCodeProvider}. * * <p>Your business logic can react to the exception code exposed * via {@link #getCode} when calling Camunda Java API and is * even exposed to the REST API when an error occurs. */ public void setCode(int code) { this.code = code; } /** * <p>Accessor of the exception error code. * * <p>If not changed via {@link #setCode}, default code is {@link BuiltinExceptionCode#FALLBACK} * which is always overridden by a custom or built-in error code provider. * * <p>You can implement a custom {@link ExceptionCodeProvider} * and register it in the {@link ProcessEngineConfigurationImpl} * via the {@code customExceptionCodeProvider} property. */ public int getCode() { return code; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\ProcessEngineException.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrintPackage other = (PrintPackage)obj; if (copies != other.copies) return false; if (format == null) { if (other.format != null) return false; } else if (!format.equals(other.format)) return false; if (pageCount != other.pageCount) return false; if (printJobInstructionsID == null) { if (other.printJobInstructionsID != null) return false; } else if (!printJobInstructionsID.equals(other.printJobInstructionsID))
return false; if (printPackageId == null) { if (other.printPackageId != null) return false; } else if (!printPackageId.equals(other.printPackageId)) return false; if (printPackageInfos == null) { if (other.printPackageInfos != null) return false; } else if (!printPackageInfos.equals(other.printPackageInfos)) return false; if (transactionId == null) { if (other.transactionId != null) return false; } else if (!transactionId.equals(other.transactionId)) return false; return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackage.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_Year[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_Calendar getC_Calendar() throws RuntimeException { return (I_C_Calendar)MTable.get(getCtx(), I_C_Calendar.Table_Name) .getPO(getC_Calendar_ID(), get_TrxName()); } /** Set Calendar. @param C_Calendar_ID Accounting Calendar Name */ public void setC_Calendar_ID (int C_Calendar_ID) { if (C_Calendar_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, Integer.valueOf(C_Calendar_ID)); } /** Get Calendar. @return Accounting Calendar Name */ public int getC_Calendar_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Calendar_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Year. @param C_Year_ID Calendar Year */ public void setC_Year_ID (int C_Year_ID) { if (C_Year_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Year_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Year_ID, Integer.valueOf(C_Year_ID)); } /** Get Year. @return Calendar Year */ public int getC_Year_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Year_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 Year. @param FiscalYear The Fiscal Year
*/ public void setFiscalYear (String FiscalYear) { set_Value (COLUMNNAME_FiscalYear, FiscalYear); } /** Get Year. @return The Fiscal Year */ public String getFiscalYear () { return (String)get_Value(COLUMNNAME_FiscalYear); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getFiscalYear()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Year.java
1
请完成以下Java代码
public final class SimpleAuthorityMapper implements GrantedAuthoritiesMapper, InitializingBean { private @Nullable GrantedAuthority defaultAuthority; private String prefix = "ROLE_"; private boolean convertToUpperCase = false; private boolean convertToLowerCase = false; @Override public void afterPropertiesSet() { Assert.isTrue(!(this.convertToUpperCase && this.convertToLowerCase), "Either convertToUpperCase or convertToLowerCase can be set to true, but not both"); } /** * Creates a mapping of the supplied authorities based on the case-conversion and * prefix settings. The mapping will be one-to-one unless duplicates are produced * during the conversion. If a default authority has been set, this will also be * assigned to each mapping. * @param authorities the original authorities * @return the converted set of authorities */ @Override public Set<GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) { HashSet<GrantedAuthority> mapped = new HashSet<>(authorities.size()); for (GrantedAuthority authority : authorities) { String authorityStr = authority.getAuthority(); if (authorityStr != null) { mapped.add(mapAuthority(authorityStr)); } } if (this.defaultAuthority != null) { mapped.add(this.defaultAuthority); } return mapped; } private GrantedAuthority mapAuthority(String name) { if (this.convertToUpperCase) { name = name.toUpperCase(Locale.ROOT); } else if (this.convertToLowerCase) { name = name.toLowerCase(Locale.ROOT); } if (this.prefix.length() > 0 && !name.startsWith(this.prefix)) { name = this.prefix + name; } return new SimpleGrantedAuthority(name); }
/** * Sets the prefix which should be added to the authority name (if it doesn't already * exist) * @param prefix the prefix, typically to satisfy the behaviour of an * {@code AccessDecisionVoter}. */ public void setPrefix(String prefix) { Assert.notNull(prefix, "prefix cannot be null"); this.prefix = prefix; } /** * Whether to convert the authority value to upper case in the mapping. * @param convertToUpperCase defaults to {@code false} */ public void setConvertToUpperCase(boolean convertToUpperCase) { this.convertToUpperCase = convertToUpperCase; } /** * Whether to convert the authority value to lower case in the mapping. * @param convertToLowerCase defaults to {@code false} */ public void setConvertToLowerCase(boolean convertToLowerCase) { this.convertToLowerCase = convertToLowerCase; } /** * Sets a default authority to be assigned to all users * @param authority the name of the authority to be assigned to all users. */ public void setDefaultAuthority(String authority) { Assert.hasText(authority, "The authority name cannot be set to an empty value"); this.defaultAuthority = new SimpleGrantedAuthority(authority); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\SimpleAuthorityMapper.java
1
请完成以下Java代码
protected VarBuilder self() { return this; } } /** * Builder for a property accessor. * * @param <T> the type of builder */ public static final class AccessorBuilder<T extends Builder<T>> { private final AnnotationContainer annotations = new AnnotationContainer(); private CodeBlock code; private final T parent; private final Consumer<Accessor> accessorFunction; private AccessorBuilder(T parent, Consumer<Accessor> accessorFunction) { this.parent = parent; this.accessorFunction = accessorFunction; } /** * Adds an annotation. * @param className the class name of the annotation * @return this for method chaining */ public AccessorBuilder<?> withAnnotation(ClassName className) { return withAnnotation(className, null); } /** * Adds an annotation. * @param className the class name of the annotation * @param annotation configurer for the annotation * @return this for method chaining */ public AccessorBuilder<?> withAnnotation(ClassName className, Consumer<Annotation.Builder> annotation) { this.annotations.addSingle(className, annotation); return this; }
/** * Sets the body. * @param code the code for the body * @return this for method chaining */ public AccessorBuilder<?> withBody(CodeBlock code) { this.code = code; return this; } /** * Builds the accessor. * @return the parent getter / setter */ public T buildAccessor() { this.accessorFunction.accept(new Accessor(this)); return this.parent; } } static final class Accessor implements Annotatable { private final AnnotationContainer annotations; private final CodeBlock code; Accessor(AccessorBuilder<?> builder) { this.annotations = builder.annotations.deepCopy(); this.code = builder.code; } CodeBlock getCode() { return this.code; } @Override public AnnotationContainer annotations() { return this.annotations; } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinPropertyDeclaration.java
1
请在Spring Boot框架中完成以下Java代码
public Builder entityId(String entityId) { return (Builder) super.entityId(entityId); } /** * {@inheritDoc} */ @Override public Builder wantAuthnRequestsSigned(boolean wantAuthnRequestsSigned) { return (Builder) super.wantAuthnRequestsSigned(wantAuthnRequestsSigned); } /** * {@inheritDoc} */ @Override public Builder signingAlgorithms(Consumer<List<String>> signingMethodAlgorithmsConsumer) { return (Builder) super.signingAlgorithms(signingMethodAlgorithmsConsumer); } /** * {@inheritDoc} */ @Override public Builder verificationX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.verificationX509Credentials(credentialsConsumer); } /** * {@inheritDoc} */ @Override public Builder encryptionX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.encryptionX509Credentials(credentialsConsumer); } /** * {@inheritDoc} */ @Override public Builder singleSignOnServiceLocation(String singleSignOnServiceLocation) { return (Builder) super.singleSignOnServiceLocation(singleSignOnServiceLocation); } /** * {@inheritDoc} */ @Override public Builder singleSignOnServiceBinding(Saml2MessageBinding singleSignOnServiceBinding) { return (Builder) super.singleSignOnServiceBinding(singleSignOnServiceBinding); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) { return (Builder) super.singleLogoutServiceLocation(singleLogoutServiceLocation); } /**
* {@inheritDoc} */ @Override public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) { return (Builder) super.singleLogoutServiceResponseLocation(singleLogoutServiceResponseLocation); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) { return (Builder) super.singleLogoutServiceBinding(singleLogoutServiceBinding); } /** * Build an * {@link org.springframework.security.saml2.provider.service.registration.OpenSamlAssertingPartyDetails} * @return */ @Override public OpenSamlAssertingPartyDetails build() { return new OpenSamlAssertingPartyDetails(super.build(), this.descriptor); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\OpenSamlAssertingPartyDetails.java
2
请完成以下Java代码
public void cacheInvalidate() { cache_retrieveEntities.reset(); cache_retrieveLookupValueById.reset(); } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.<CCacheStats>builder() .add(cache_retrieveEntities.stats()) .add(cache_retrieveLookupValueById.stats()) .addAll(delegate.getCacheStats()) .build(); } @Override public boolean isNumericKey() { return delegate.isNumericKey(); } @Override public LookupDataSourceContext.Builder newContextForFetchingById(final Object id) { return delegate.newContextForFetchingById(id); } @Override public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx) { return cache_retrieveLookupValueById.getOrLoad(evalCtx, () -> delegate.retrieveLookupValueById(evalCtx)); } @Override
public LookupValuesList retrieveLookupValueByIdsInOrder(final @NonNull LookupDataSourceContext evalCtx) { cache_retrieveLookupValueById.getAllOrLoad( evalCtx.streamSingleIdContexts().collect(ImmutableSet.toImmutableSet()), singleIdCtxs -> { final LookupDataSourceContext multipleIdsCtx = LookupDataSourceContext.mergeToMultipleIds(singleIdCtxs); return delegate.retrieveLookupValueByIdsInOrder(LookupDataSourceContext.mergeToMultipleIds(singleIdCtxs)) .getValues() .stream() .collect(ImmutableMap.toImmutableMap( lookupValue -> multipleIdsCtx.withIdToFilter(IdsToFilter.ofSingleValue(lookupValue.getId())), lookupValue -> lookupValue)); } ); return LookupDataSourceFetcher.super.retrieveLookupValueByIdsInOrder(evalCtx); } @Override public Builder newContextForFetchingList() { return delegate.newContextForFetchingList(); } @Override public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) { return cache_retrieveEntities.getOrLoad(evalCtx, delegate::retrieveEntities); } @Override public Optional<WindowId> getZoomIntoWindowId() { return delegate.getZoomIntoWindowId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\CachedLookupDataSourceFetcherAdapter.java
1
请完成以下Java代码
public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("QualityInspectionLinesCollection["); if (!lines.isEmpty()) { for (final IQualityInspectionLine line : lines) { sb.append("\n\t").append(line); } sb.append("\n"); // new line after last one } else { sb.append("empty"); } sb.append("]"); return sb.toString(); } @Override public IQualityInspectionLine getByType(final QualityInspectionLineType type) { final List<IQualityInspectionLine> linesFound = getAllByType(type); if (linesFound.isEmpty()) { throw new AdempiereException("No line found for type: " + type); } else if (linesFound.size() > 1) { throw new AdempiereException("More then one line found for type " + type + ": " + linesFound); } return linesFound.get(0); } @Override public List<IQualityInspectionLine> getAllByType(final QualityInspectionLineType... types) { Check.assumeNotEmpty(types, "types not empty"); final List<QualityInspectionLineType> typesList = Arrays.asList(types);
final List<IQualityInspectionLine> linesFound = new ArrayList<>(); for (final IQualityInspectionLine line : lines) { final QualityInspectionLineType lineType = line.getQualityInspectionLineType(); if (typesList.contains(lineType)) { linesFound.add(line); } } return linesFound; } @Override public IQualityInspectionOrder getQualityInspectionOrder() { return this.qiOrder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLinesCollection.java
1
请完成以下Java代码
private FirebaseSignInResponse sendSignInRequest(FirebaseSignInRequest firebaseSignInRequest) { try { return RestClient.create(SIGN_IN_BASE_URL) .post() .uri(uriBuilder -> uriBuilder .queryParam(API_KEY_PARAM, webApiKey) .build()) .body(firebaseSignInRequest) .contentType(MediaType.APPLICATION_JSON) .retrieve() .body(FirebaseSignInResponse.class); } catch (HttpClientErrorException exception) { if (exception.getResponseBodyAsString().contains(INVALID_CREDENTIALS_ERROR)) { throw new InvalidLoginCredentialsException("Invalid login credentials provided"); } throw exception; } } private RefreshTokenResponse sendRefreshTokenRequest(RefreshTokenRequest refreshTokenRequest) { try { return RestClient.create(REFRESH_TOKEN_BASE_URL) .post() .uri(uriBuilder -> uriBuilder .queryParam(API_KEY_PARAM, webApiKey) .build()) .body(refreshTokenRequest) .contentType(MediaType.APPLICATION_JSON) .retrieve() .body(RefreshTokenResponse.class); } catch (HttpClientErrorException exception) { if (exception.getResponseBodyAsString().contains(INVALID_REFRESH_TOKEN_ERROR)) {
throw new InvalidRefreshTokenException("Invalid refresh token provided"); } throw exception; } } record FirebaseSignInRequest(String email, String password, boolean returnSecureToken) { } record FirebaseSignInResponse(String idToken, String refreshToken) { } record RefreshTokenRequest(String grant_type, String refresh_token) { } record RefreshTokenResponse(String id_token) { } }
repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\auth\FirebaseAuthClient.java
1
请完成以下Java代码
protected long hitCount() { return this.cache.getStatistics().getHits(); } @Override protected Long missCount() { return this.cache.getStatistics().getMisses(); } @Override protected @Nullable Long evictionCount() { return null; } @Override protected long putCount() { return this.cache.getStatistics().getPuts(); } @Override protected void bindImplementationSpecificMetrics(MeterRegistry registry) { FunctionCounter.builder("cache.removals", this.cache, (cache) -> cache.getStatistics().getDeletes()) .tags(getTagsWithCacheName()) .description("Cache removals")
.register(registry); FunctionCounter.builder("cache.gets", this.cache, (cache) -> cache.getStatistics().getPending()) .tags(getTagsWithCacheName()) .tag("result", "pending") .description("The number of pending requests") .register(registry); TimeGauge .builder("cache.lock.duration", this.cache, TimeUnit.NANOSECONDS, (cache) -> cache.getStatistics().getLockWaitDuration(TimeUnit.NANOSECONDS)) .tags(getTagsWithCacheName()) .description("The time the cache has spent waiting on a lock") .register(registry); } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\metrics\RedisCacheMetrics.java
1
请完成以下Java代码
public class MessageSubscriptionCancelledListenerDelegate implements ActivitiEventListener { private List<ProcessRuntimeEventListener<MessageSubscriptionCancelledEvent>> processRuntimeEventListeners; private ToMessageSubscriptionCancelledConverter converter; public MessageSubscriptionCancelledListenerDelegate( List<ProcessRuntimeEventListener<MessageSubscriptionCancelledEvent>> processRuntimeEventListeners, ToMessageSubscriptionCancelledConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override public void onEvent(ActivitiEvent event) { if (isValidEvent(event)) { converter .from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { processRuntimeEventListeners.forEach(listener -> listener.onEvent(convertedEvent));
}); } } @Override public boolean isFailOnException() { return false; } protected boolean isValidEvent(ActivitiEvent event) { return Optional.ofNullable(event) .filter(ActivitiEntityEvent.class::isInstance) .map(e -> ((ActivitiEntityEvent) event).getEntity() instanceof MessageEventSubscriptionEntity) .orElse(false); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\MessageSubscriptionCancelledListenerDelegate.java
1
请完成以下Java代码
public Criteria andSortIn(List<Integer> values) { addCriterion("sort in", values, "sort"); return (Criteria) this; } public Criteria andSortNotIn(List<Integer> values) { addCriterion("sort not in", values, "sort"); return (Criteria) this; } public Criteria andSortBetween(Integer value1, Integer value2) { addCriterion("sort between", value1, value2, "sort"); return (Criteria) this; } public Criteria andSortNotBetween(Integer value1, Integer value2) { addCriterion("sort not between", value1, value2, "sort"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super();
this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelpCategoryExample.java
1
请在Spring Boot框架中完成以下Java代码
public class SunJaasKrb5LoginConfig extends Configuration implements InitializingBean { private static final Log LOG = LogFactory.getLog(SunJaasKrb5LoginConfig.class); private String servicePrincipal; private Resource keyTabLocation; private Boolean useTicketCache = false; private Boolean isInitiator = false; private Boolean debug = false; private String keyTabLocationAsString; public void setServicePrincipal(String servicePrincipal) { this.servicePrincipal = servicePrincipal; } public void setKeyTabLocation(Resource keyTabLocation) { this.keyTabLocation = keyTabLocation; } public void setUseTicketCache(Boolean useTicketCache) { this.useTicketCache = useTicketCache; } public void setIsInitiator(Boolean isInitiator) { this.isInitiator = isInitiator; } public void setDebug(Boolean debug) { this.debug = debug; } @Override public void afterPropertiesSet() throws Exception { Assert.hasText(this.servicePrincipal, "servicePrincipal must be specified"); if (this.keyTabLocation != null && this.keyTabLocation instanceof ClassPathResource) { LOG.warn(
"Your keytab is in the classpath. This file needs special protection and shouldn't be in the classpath. JAAS may also not be able to load this file from classpath."); } if (!this.useTicketCache) { Assert.notNull(this.keyTabLocation, "keyTabLocation must be specified when useTicketCache is false"); } if (this.keyTabLocation != null) { this.keyTabLocationAsString = this.keyTabLocation.getURL().toExternalForm(); if (this.keyTabLocationAsString.startsWith("file:")) { this.keyTabLocationAsString = this.keyTabLocationAsString.substring(5); } } } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { HashMap<String, String> options = new HashMap<>(); options.put("principal", this.servicePrincipal); if (this.keyTabLocation != null) { options.put("useKeyTab", "true"); options.put("keyTab", this.keyTabLocationAsString); options.put("storeKey", "true"); } options.put("doNotPrompt", "true"); if (this.useTicketCache) { options.put("useTicketCache", "true"); options.put("renewTGT", "true"); } options.put("isInitiator", this.isInitiator.toString()); options.put("debug", this.debug.toString()); return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), }; } }
repos\spring-security-main\kerberos\kerberos-client\src\main\java\org\springframework\security\kerberos\client\config\SunJaasKrb5LoginConfig.java
2
请完成以下Java代码
public static <T extends Message> void broadcast(String type, T message) { // 创建消息 TextMessage textMessage = buildTextMessage(type, message); // 遍历 SESSION_USER_MAP ,进行逐个发送 for (WebSocketSession session : SESSION_USER_MAP.keySet()) { sendTextMessage(session, textMessage); } } /** * 发送消息给单个用户的 Session * * @param session Session * @param type 消息类型 * @param message 消息体 * @param <T> 消息类型 */ public static <T extends Message> void send(WebSocketSession session, String type, T message) { // 创建消息 TextMessage textMessage = buildTextMessage(type, message); // 遍历给单个 Session ,进行逐个发送 sendTextMessage(session, textMessage); } /** * 发送消息给指定用户 * * @param user 指定用户 * @param type 消息类型 * @param message 消息体 * @param <T> 消息类型 * @return 发送是否成功你那个 */ public static <T extends Message> boolean send(String user, String type, T message) { // 获得用户对应的 Session WebSocketSession session = USER_SESSION_MAP.get(user); if (session == null) { LOGGER.error("[send][user({}) 不存在对应的 session]", user); return false; } // 发送消息 send(session, type, message); return true; } /** * 构建完整的消息
* * @param type 消息类型 * @param message 消息体 * @param <T> 消息类型 * @return 消息 */ private static <T extends Message> TextMessage buildTextMessage(String type, T message) { JSONObject messageObject = new JSONObject(); messageObject.put("type", type); messageObject.put("body", message); return new TextMessage(messageObject.toString()); } /** * 真正发送消息 * * @param session Session * @param textMessage 消息 */ private static void sendTextMessage(WebSocketSession session, TextMessage textMessage) { if (session == null) { LOGGER.error("[sendTextMessage][session 为 null]"); return; } try { session.sendMessage(textMessage); } catch (IOException e) { LOGGER.error("[sendTextMessage][session({}) 发送消息{}) 发生异常", session, textMessage, e); } } }
repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-02\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\util\WebSocketUtil.java
1
请完成以下Java代码
public void setAD_ImpFormat(final org.compiere.model.I_AD_ImpFormat AD_ImpFormat) { set_ValueFromPO(COLUMNNAME_AD_ImpFormat_ID, org.compiere.model.I_AD_ImpFormat.class, AD_ImpFormat); } @Override public void setAD_ImpFormat_ID (final int AD_ImpFormat_ID) { if (AD_ImpFormat_ID < 1) set_Value (COLUMNNAME_AD_ImpFormat_ID, null); else set_Value (COLUMNNAME_AD_ImpFormat_ID, AD_ImpFormat_ID); } @Override public int getAD_ImpFormat_ID() { return get_ValueAsInt(COLUMNNAME_AD_ImpFormat_ID); } @Override public void setC_DataImport_ID (final int C_DataImport_ID) { if (C_DataImport_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, C_DataImport_ID); } @Override public int getC_DataImport_ID() { return get_ValueAsInt(COLUMNNAME_C_DataImport_ID); } /** * DataImport_ConfigType AD_Reference_ID=541535 * Reference name: C_DataImport_ConfigType */ public static final int DATAIMPORT_CONFIGTYPE_AD_Reference_ID=541535;
/** Standard = S */ public static final String DATAIMPORT_CONFIGTYPE_Standard = "S"; /** Bank Statement Import = BSI */ public static final String DATAIMPORT_CONFIGTYPE_BankStatementImport = "BSI"; @Override public void setDataImport_ConfigType (final java.lang.String DataImport_ConfigType) { set_Value (COLUMNNAME_DataImport_ConfigType, DataImport_ConfigType); } @Override public java.lang.String getDataImport_ConfigType() { return get_ValueAsString(COLUMNNAME_DataImport_ConfigType); } @Override public void setInternalName (final @Nullable java.lang.String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public java.lang.String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DataImport.java
1
请完成以下Java代码
public long countByCriteria(CaseInstanceQueryImpl query) { setSafeInValueLists(query); return (Long) getDbSqlSession().selectOne("selectCaseInstanceCountByQueryCriteria", query); } @Override public void updateLockTime(String caseInstanceId, Date lockDate, String lockOwner, Date expirationTime) { HashMap<String, Object> params = new HashMap<>(); params.put("id", caseInstanceId); params.put("lockTime", lockDate); params.put("expirationTime", expirationTime); params.put("lockOwner", lockOwner); int result = getDbSqlSession().directUpdate("updateCaseInstanceLockTime", params); if (result == 0) { throw new FlowableOptimisticLockingException("Could not lock case instance"); } } @Override public void clearLockTime(String caseInstanceId) { HashMap<String, Object> params = new HashMap<>(); params.put("id", caseInstanceId); getDbSqlSession().directUpdate("clearCaseInstanceLockTime", params); } @Override public void clearAllLockTimes(String lockOwner) { HashMap<String, Object> params = new HashMap<>();
params.put("lockOwner", lockOwner); getDbSqlSession().directUpdate("clearAllCaseInstanceLockTimes", params); } protected void setSafeInValueLists(CaseInstanceQueryImpl caseInstanceQuery) { if (caseInstanceQuery.getCaseInstanceIds() != null) { caseInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(caseInstanceQuery.getCaseInstanceIds())); } if (caseInstanceQuery.getInvolvedGroups() != null) { caseInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(caseInstanceQuery.getInvolvedGroups())); } if (caseInstanceQuery.getOrQueryObjects() != null && !caseInstanceQuery.getOrQueryObjects().isEmpty()) { for (CaseInstanceQueryImpl orCaseInstanceQuery : caseInstanceQuery.getOrQueryObjects()) { setSafeInValueLists(orCaseInstanceQuery); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisCaseInstanceDataManagerImpl.java
1
请完成以下Java代码
public static DeliveryPosition deliveryPositionFromPO(final I_GO_DeliveryOrder orderPO, final Set<PackageId> mpackageIds) { return DeliveryPosition.builder() .numberOfPackages(orderPO.getGO_NumberOfPackages()) .packageIds(mpackageIds) .grossWeightKg(BigDecimal.valueOf(orderPO.getGO_GrossWeightKg())) .content(orderPO.getGO_PackageContentDescription()) .build(); } public static void deliveryPositionToPO(final I_GO_DeliveryOrder orderPO, final DeliveryPosition deliveryPosition) { orderPO.setGO_NumberOfPackages(deliveryPosition.getNumberOfPackages()); final int go_grossWeightKg = deliveryPosition.getGrossWeightKg() .setScale(0, RoundingMode.UP) .intValue(); orderPO.setGO_GrossWeightKg(go_grossWeightKg); orderPO.setGO_PackageContentDescription(deliveryPosition.getContent()); }
// ------------ private static int createC_Location_ID(final Address address) { final I_C_Location locationPO = InterfaceWrapperHelper.newInstanceOutOfTrx(I_C_Location.class); locationPO.setAddress1(address.getStreet1()); locationPO.setAddress2(address.getStreet2()); locationPO.setAddress3(address.getHouseNo()); locationPO.setPostal(address.getZipCode()); locationPO.setCity(address.getCity()); final String countryCode2 = address.getCountry().getAlpha2(); final I_C_Country country = Services.get(ICountryDAO.class).retrieveCountryByCountryCode(countryCode2); locationPO.setC_Country(country); InterfaceWrapperHelper.save(locationPO); return locationPO.getC_Location_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GODeliveryOrderConverters.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderQtyChangeRequest { @NonNull PPOrderId ppOrderId; @NonNull Quantity qtyReceivedToAdd; @NonNull Quantity qtyScrappedToAdd; @NonNull Quantity qtyRejectedToAdd; @NonNull ZonedDateTime date; @Builder(toBuilder = true) private OrderQtyChangeRequest( @NonNull final PPOrderId ppOrderId, @Nullable final Quantity qtyReceivedToAdd, @Nullable final Quantity qtyScrappedToAdd, @Nullable final Quantity qtyRejectedToAdd, @NonNull final ZonedDateTime date) { final Quantity firstNonNullQty = CoalesceUtil.coalesce(qtyReceivedToAdd, qtyScrappedToAdd, qtyRejectedToAdd); if (firstNonNullQty == null) { throw new AdempiereException("At least one of the qtys shall be non-null"); }
this.ppOrderId = ppOrderId; this.qtyReceivedToAdd = qtyReceivedToAdd != null ? qtyReceivedToAdd : firstNonNullQty.toZero(); this.qtyScrappedToAdd = qtyScrappedToAdd != null ? qtyScrappedToAdd : firstNonNullQty.toZero(); this.qtyRejectedToAdd = qtyRejectedToAdd != null ? qtyRejectedToAdd : firstNonNullQty.toZero(); this.date = date; } public OrderQtyChangeRequest convertQuantities(@NonNull final UnaryOperator<Quantity> converter) { return toBuilder() .qtyReceivedToAdd(converter.apply(getQtyReceivedToAdd())) .qtyScrappedToAdd(converter.apply(getQtyScrappedToAdd())) .qtyRejectedToAdd(converter.apply(getQtyRejectedToAdd())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\OrderQtyChangeRequest.java
2
请完成以下Java代码
public void setDateTo (Timestamp DateTo) { set_Value (COLUMNNAME_DateTo, DateTo); } /** Get Date To. @return End date of a date range */ public Timestamp getDateTo () { return (Timestamp)get_Value(COLUMNNAME_DateTo); } /** 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 GL Fund. @param GL_Fund_ID General Ledger Funds Control */ public void setGL_Fund_ID (int GL_Fund_ID) { if (GL_Fund_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, Integer.valueOf(GL_Fund_ID)); } /** Get GL Fund. @return General Ledger Funds Control */ public int getGL_Fund_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID); if (ii == null) return 0; return ii.intValue(); } /** 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 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_GL_Fund.java
1